/* Bind to multiple Backbone.js View Model's fetch completion with jQuery Deferred */
var Model1 = Backbone.Model.extend({
// Using the response from https://gist.github.com/4531534
url: '/gh/gist/response.json/4531534/',
});
var Model2 = Backbone.Model.extend({
// Using the response from https://gist.github.com/4535771
url: '/gh/gist/response.json/4535771/',
});
var View = Backbone.View.extend({
initialize: function () {
var _thisView = this;
// This uses jQuery's Deferred functionality to bind render() so it runs
// after BOTH models have been fetched
$.when(this.options.model1.fetch(),this.options.model2.fetch())
.done(function () {
_thisView.render();
});
},
render: function () {
// log the number of times render() is called
$('<li>').html('calling render()').appendTo('#log');
// Lets just output the response into the DOM
$('pre').html(JSON.stringify(this.options.model1.toJSON(), '', ' '));
$('pre').append(JSON.stringify(this.options.model2.toJSON(), '', ' '));
}
});
// Initialize the Model
var myModel = new Model1();
var myOtherModel = new Model2();
// Initialize the View, passing it the model instance
var myView = new View({
model1: myModel,
model2: myOtherModel
});
<a href="http://chilipepperdesign.com/2013/01/14/backbone-js-bind-callback-to-successful-model-fetch/">Bind to multiple Backbone.js View Model's fetch completion with jQuery Deferred</a>
<ul id="log"></ul>
<hr />
<pre>Loading...</pre>
a {
font-family: arial, sans;
margin-bottom: 2em;
color: #000;
display:inline-block;
font-size: 12px;
}
External resources loaded into this fiddle: