My Backbone app includes Views which depend on multiple models. For example, I define 2 models:
var user = new UserModel({id:1});
user.fetch();
var place = new PlaceModel({id:1});
place.fetch();
Now I want to render a View that depends on both these models:
var home = new House({owner: user, address: place});
home.render()
I don’t want to render the View until I’m sure all the models have loaded.
What is the right way to make sure that user and place have both been fetched before I render home?
I’m currently using a sequential process:
user.bind("change", function() {place.fetch();});
place.bind("change", function() {home.render();});
user.fetch();
But this gets unwieldy as the dependencies grow and I feel like there must be a better way…
Backbone
fetchuses jQuery for AJAX calls, and like a plain$.ajaxcall, returns a jQuery Deferred object.This means that waiting for multiple calls to finish can be done quite elegantly using
$.when:Edit: Earlier version of this answer claimed that Backbone.localStorage does not return a deferred, but it does, so this solution also works with that plugin.