Skip to content

Instantly share code, notes, and snippets.

@sukima
Created January 8, 2014 18:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sukima/8321859 to your computer and use it in GitHub Desktop.
Save sukima/8321859 to your computer and use it in GitHub Desktop.
exports.definition = {
config: {
columns: {
// ...
},
adapter: {
type: "sql",
collection_name: "MyModels"
}
},
extendCollection: function(Collection) {
Collection.prototype.destroyAll = function(opt) {
var db = Ti.Database.open(this.config.adapter.db_name);
db.execute("DELETE FROM " + this.config.adapter.collection_name);
db.close();
this.models = [];
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
};
Collection.prototype.saveAll = function(opt) {
var util = require("alloy/sync/util");
var dbName = this.config.adapter.db_name;
var table = this.config.adapter.collection_name;
var columns = this.config.columns;
var db = Ti.Database.open(dbName);
db.execute("BEGIN;");
this.forEach(function (model) {
if (!model.id) {
model.id = util.guid();
model.attributes[model.idAttribute ] = model.id;
}
var names = [], values = [], q = [];
for (var k in columns) {
names.push(k);
values.push(model.get(k));
q.push("?");
}
var sqlInsert = "INSERT INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
db.execute(sqlInsert, values);
});
db.execute("COMMIT;");
db.close();
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
};
Collection.prototype.refreshFromData = function refreshFromData(data) {
this.destroyAll({silent:true});
this.reset(data, {silent:true});
this.saveAll({silent: true});
this.trigger("fetch");
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment