I’d like to be able to use jQuery’s Deferred object to operate loading data via Backbone Collections and Models. Is there any way I can modify the arguments provided to the done and fail callbacks to include the Model or Collection instance? I’m envisioning something like the following:
var _sync = Backbone.sync;
Backbone.sync = function() {
var jqXhr = _sync.apply(this, arguments);
var self = this;
return jqXhr.pipe(function() {
var cbArgs = [self];
cbArgs.push.apply(cbArgs, arguments);
return cbArgs;
}
}
...
var c = new Backbone.Collection();
c.url = "/path/to/resources";
c.fetch().then(function(collection, data, textStatus, jqXhr) {
// do stuff with collection
});
Of course, since filter is returning an array, the done callback is invoked with an array, rather than the enumerated arguments. As far as I can see, pipe can only modify provided arguments, not add. Any suggestions would be appreciated.
Edit: This is a very simplified example; since a closure is created over the original collection, I could just operate on that. However, the use case is that multiple Backbone Views might rely on the same data being fetched, so I’d like to be able to just supply the jQuery Deferred object to these views, rather than both the Deferred and the collection instance.
Another Edit: Posted a solution below, but any other suggestions welcome.
I’ve found I can accomplish this by having the .pipe method return a new $.Deferred that is immediately resolved using the modified arguments: