Last active
January 3, 2016 13:19
-
-
Save morganney/8468520 to your computer and use it in GitHub Desktop.
Using JavaScript Promises with Backbone.sync
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
| // 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