Skip to content

Instantly share code, notes, and snippets.

@chrisjhoughton
Last active August 14, 2022 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisjhoughton/5408493 to your computer and use it in GitHub Desktop.
Save chrisjhoughton/5408493 to your computer and use it in GitHub Desktop.
Backbone Sync with jQuery and a REST API
/*
Overview:
- triggers "sync", "sync_success" and "sync_error" messages after sync
- runs this.url() on the model/collection inputted (note - this function is declared by default in models, not collections. See http://backbonejs.org/#Collection-url for more details)
- handles the four main REST api methods: POST, PUT, GET, DELETE
- expects 'create' to return an id, which is auto-set to the newly created model
- automatically sets parameters when 'fetching' models
- automatically adds models to collections when 'fetching' collections
EXAMPLES:
E.g. 1: Fetching a model ('GET') from the database, by id.
var MyModel = Backbone.Model.extend({
urlRoot: 'apps',
});
var model = new MyModel({ id: 123456 });
model.on('sync', function() {
// we can now access the model parameters in model/this
});
model.fetch();
E.g. 2: Creating a new model in the database with a set of parameters that the user has inputted
var model = new MyModel();
model.set({
name: 'chris',
age: 23,
favorite_color: 'red'
});
model.on('sync', function() {
// model has been saved, the 'id' should now be assigned to the model.
});
model.save();
E.g. 3: Deleting a model in the database
var model = new MyModel({ id: 123456 });
model.on('sync', function() {
// model has now been deleted in the database
});
model.destroy();
*/
// Overrides the backbone sync function
Backbone.sync = function(method, model, options) {
var _this = this;
options = options || {};
switch (method) {
case 'create':
$.ajax({
method: 'POST',
url: '/api/'+this.url(), // url() needs to be manually declared in collections
data: JSON.stringify(model.attributes),
dataType: 'json', // the data type we're expecting back from the server
contentType: 'application/json', // the data type we're sending to the server
success: function(result) {
model.set('id', result);
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_success');
},
error: function (result) {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_error');
}
});
break;
case 'update':
$.ajax({
method: 'PUT',
url: '/api/'+this.url(),
data: JSON.stringify(model.attributes),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_success');
},
error: function (result) {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_error');
}
});
break;
case 'delete':
$.ajax({
method: 'DELETE',
url: '/api/'+this.url(),
data: JSON.stringify(model.attributes),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_success');
},
error: function (result) {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_error');
}
});
break;
case 'read':
$.ajax({
method: 'GET',
url: '/api/'+this.url(),
dataType: 'json',
success: function(result) {
if (result) {
if (model instanceof Backbone.Model) {
model.set(result);
} else if (model instanceof Backbone.Collection) {
model.add(result);
}
}
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_success');
},
error: function () {
model.hasSynced = true;
model.trigger('sync');
model.trigger('sync_error');
}
});
break;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment