In this blog post I will explain how Backbone.js models can be extended to return an A+ Promise, rather than jQuery’s jqXHR object.
In Backbone, a Model is used to:
- Orchestrate data and business logic.
- Load and save from the server.
- Emit events when data changes.
Backbone uses a function called
Backbone.sync every time it attempts to read or save a model to the server. For example, this function is used every time you invoke
.destroy() on a model. By default, it uses
Backbone.ajax to make a RESTful JSON request and returns a jqXHR object from jQuery.
As of jQuery 1.5 the jqXHR object implements a Promise interface, giving them all the properties, methods, and behaviors of a Promise (see Deferred object).
A+ Promise instead of jqXHR
When working with Promises, I prefer to use Bluebird - which implements the A+ Promise Standard. For example, rather than using jQuery’s
.always I prefer to use
.finally from Bluebird. This helps ensure all my asynchronous code is inline with the A+ specification.
With Backbone you can override the default behavior for both
Backbone.syncto use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.
Backbone.ajaxif you want to use a custom AJAX function, or your endpoint doesn’t support the
Because we still want to use AJAX, in this example, we will override
Backbone.ajax. This is the default implementation:
We can use Bluebird’s
Promise.resolve function to convert jQuery’s
jqXHR object to an A+ Promise.
This also works for
.fetch on a Backbone Collection.