Question

I am currently creating a Backbone.js and jquery Mobile web application and I have some calls to Backbone.model.fetch(). I have the proper success and error-callbacks, but there is some code that I want to execute no matter if the fetch was successfull or not.

Currently, I'm simply copying the common code. But I asked myself if there is any callback that is executed no matter what happens.

Like the try{} catch{} finally{} from C#. Is there anything like that?

Was it helpful?

Solution

fetch() returns a 'Deferred Object' see: http://api.jquery.com/category/deferred-object/

it's not really like try{} catch{}, but you can use .always() method to bind a callback which will be executed after the request is done (no matter if it was successful or not)

like so.

 var doSomething = function () {
     //will run after fetch() request is finished
 };

 collection.fetch().always(doSomething);

similarly, instead of passing success or error callbacks to fetch()'s options, in general it is encouraged to chain .done(), .fail(), or .then() methods to deferred methods(fetch, save...etc)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top