First sorry for my horrible english. This is the first time I’m using backbone.js.
I need to render a view to list my products but I need to fetch 2 selects () with product families and product types in the same place.
How can I fetch 3 collections in the same view? The fetches are asynchronous and need to capture the models on a successful response, but out the success method, I can’t read the response. Do I need to make nested fetches?
list: function () {
var families = new FamilyList();
families.fetch({
add: true,
data: {
'company_id': 1
},
success: function (model, response) {}
});
var types = new TypesList();
types.fetch({
add: true,
data: {
'company_id': 1
},
success: function (model, response) {}
});
var pr = new ProductList();
pr.fetch({
add: true,
data: {
'company_id': 1
},
success: function (model, response) {}
});
var json_template = {
"title_list": "Company product manager",
"types": types.models,
"families": families.models,
"products": pr.models,
};
html_content = Mustache.to_html(template_products, json_template);
$("#content").html(html_content);
}
You will have to render your view in a callback function. You can listen to the reset event of your collections (triggered when fetch has finished) and trigger the rendering:
You should keep in mind that you are instantiating and binding your collections whenever you call the list() function. You should consider using the initialize() function of your view to create instances and bind to their events. See:
http://documentcloud.github.com/backbone/#Collection-constructor
With this approach the list will render 3 times (once for each collection). To optimize this you can keep track of the number of collections that have finished loading, and only render if all collection callbacks have been executed.