Asked By: Anonymous
I am looking to daisy chain Backbone requests in which the second request is dependent on the result of the first. How do I do it the right way? jQuery $.done()
does not seem to work for me the right way. To explain better, here is a hypothetical example:
I have a list of suppliers and each supplier has a list of parts that they supply to the company. I want to fetch all the suppliers and then fetch all parts for this list of suppliers. Here is a sample code that I am trying to use without luck.
var App = {};
App.Supplier = Backbone.Model.extend({ });
App.Part = Backbone.Model.extend({ });
App.Suppliers = Backbone.Collection.extend({
model: App.Supplier
});
App.Parts = Backbone.Collection.extend({
model: App.Part
})
var suppliers = new App.Suppliers;
var parts = new App.Parts;
var supplier_request = suppliers.fetch();
supplier_request.done(function(){
parts.fetch_by_suppliers([supplier1, supplier2, ...]);
});
What happens is the second request fires immediately after the first reply has been received and before the App.Supplier
models are instantiated. The result is — the supplier list remains empty and the second request fires off with the empty list of suppliers.
Solution
Answered By: Anonymous
In order to accomplish this daisy chaining you’ll want to pass a success callback to the fetch
method. The success
callback gets passed (collection, response)
as arguments. You can rewrite the code in your example in the following way:
...
suppliers.fetch({success:
function(collection, response){
parts.fetch_by_suppliers(collection);
}
});
The Backbone.js documentation explains it pretty well. http://documentcloud.github.com/backbone/#Collection-fetch
Hope this helps ya!