How to load multiple, dependent Backbone models?

backbone.js, javascript-framework, requirejs

Solution

Backbone `fetch` uses jQuery for AJAX calls, and like a plain `$.ajax` call, returns a jQuery Deferred object.

This means that waiting for multiple calls to finish can be done quite elegantly using `$.when`:

var place = new PlaceModel({id:96});
var user = new UserModel({id:2458});
var home = new House({owner: user, address: place});

//both .fetch() calls return a promise
//when waits for promises to be fulfilled (or rejected)
$.when(place.fetch(), user.fetch())
  .done(home.render);
  .fail(showError);

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.

Problem

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...

Original source