How to know when a Backbone model.fetch() completes?

user1031947 picture user1031947 · Feb 17, 2013 · Viewed 11.1k times · Source

I bind on the change event of my backbone models like this.

this.model.on( "change", this.render, this );

Sometimes I want to fetch the latest version of the model and forcibly render the view. So I do this

this.model.fetch();

Unfortunately model.fetch() only fires the change event if the new data is different from what was previously stored in the model.

How can I always trigger a this.render callback when fetch completes, whether it triggers a change event or not?

Thanks (in advance) for your help

Answer

Ben picture Ben · Feb 17, 2013

You can use the $.ajax success callback, but you can also just listen for the Backbone sync and error events on the model. sync fires after a successful call to the server, error fires after a failed call to the server.

this.model.on('sync', this.render, this);
this.model.on('error', this.handleError, this);