Skip to content

Instantly share code, notes, and snippets.

@apueee
Forked from ajaxray/backbone_tide_sync.js
Created June 28, 2013 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apueee/5886191 to your computer and use it in GitHub Desktop.
Save apueee/5886191 to your computer and use it in GitHub Desktop.
Backbone.sync = function(method, model, options) {
// App.db is my database connection
if(_.isNull(App.db)) console.error('No Database connection!');
var query = BackboneDb.createQuery(method, model);
if (method === "read") {
var data = App.db.execute(query);
var resultJSON = BackboneDb.resultToJSON(data);
// console.log(data);
// console.log(resultJSON);
// If it's not a collection, use first value only
if(_.isUndefined(model.models)) {
resultJSON = resultJSON[0] || null;
}
// simulate a normal async network call
setTimeout(function(){
options.success(resultJSON, 'success', null);
}, 0);
}
};
var BackboneDb = function() {
return {
resultToJSON: function(rows) {
var result = [];
while (rows.isValidRow()) {
var row = {};
_(rows.fieldCount()).times(function(i){
row[rows.fieldName(i)] = rows.field(i);
});
result.push(row);
rows.next();
}
return result;
},
createQuery: function(method, model) {
// For models, it's a funciton
var url = _.isFunction(model.url)? model.url() : model.url;
var parts = _.compact(url.split('/'));
if(parts.length === 0) return false;
var table = parts[0];
var id = parts[1] || null;
var query = null;
if(method == 'read'){
query = 'SELECT * FROM ' + table;
if(id) {
query += ' WHERE id = ' + id;
}
}
return query;
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment