Created
January 8, 2014 18:31
-
-
Save sukima/8321859 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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