Skip to content

Instantly share code, notes, and snippets.

@morganney
Last active January 3, 2016 13:19
Show Gist options
  • Select an option

  • Save morganney/8468520 to your computer and use it in GitHub Desktop.

Select an option

Save morganney/8468520 to your computer and use it in GitHub Desktop.
Using JavaScript Promises with Backbone.sync
// Example of using JavaScript Promises with Backbone.sync
// instead of the usual success()/error() callbacks.
//
// This is a totally contrived example but does demonstrate
// using promises when syncing your Backbone models and collections.
var Model = Backbone.Model.extend({
// Some model used outside of a collection.
urlRoot: '/models'
}),
Collection = Backbone.Collection.extend({
// Some collection with a dependency on 'Model'.
initialize: function(models, options) {
this.dependency = options.dependency;
},
// By using it to build a dynamic url.
url: function() {
return '/models/' + this.dependency.get('type')
}
}), m = new Model({id: 'xyz'}), c;
// ... Any pre-sync code ...
// Now when syncing update the usual Backbone workflow with promises
Promise.cast(m.fetch()).then(function(response) {
console.log(response instanceof Backbone.Model); // False, 'response' is raw server response.
console.log(m.hasChanged()); // True, the parse()'d attributes have been set() on the model.
// Now we can construct our collection passing in the resolved dependency.
c = new Collection([], {dependency: m});
// Return a promise of a fetched collection.
return Promise.cast(c.fetch());
}).then(function(response) {
// Now process the collection or chain more asynchronous actions.
}).catch(function(error) {
// Error handling for any preceding async actions.
// Here 'error' is a jQuery jqXHR object.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment