/* Backbone.js Bind Callback to Successful Model Fetch */
var Model = Backbone.Model.extend({
// Using the response from https://gist.github.com/4531534
url: '/gh/gist/response.json/4531534/',
});
var View = Backbone.View.extend({
initialize: function () {
var _thisView = this;
// #1
// This works, as long as you remember to pass in the 'this' context
// as the last parameter.
//this.model.on('change', this.render, this); // one way to bind callback
this.listenTo(this.model,'change', this.render);
this.model.fetch();
// #2
// This will work, but you have to call bindAll to make sure 'this' refers
// to the view in render() when it's called (so this.model works).
_.bindAll(this, "render");
this.model.fetch({
success: _thisView.render
});
// #3
// This uses jQuery's Deferred functionality to bind render() to the model's
// fetch promise, which is called after the AJAX request completes
this.model.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').append(JSON.stringify(this.model.toJSON(), '', ' '));
}
});
// Initialize the Model
var myModel = new Model();
// Initialize the View, passing it the model instance
var myView = new View({
model: myModel
});
// Calling fetch here will work with the model bind to 'change' in the View
//myModel.fetch();
<a href="http://chilipepperdesign.com/2013/01/14/backbone-js-bind-callback-to-successful-model-fetch/">Backbone.js Bind Callback to Successful Model Fetch</a>
<ul id="log"></ul>
<hr />
<pre></pre>
a {
font-family: arial, sans;
margin-bottom: 2em;
color: #000;
display:inline-block;
font-size: 12px;
}
External resources loaded into this fiddle: