0

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?

Manuel Hoffmann
  • 539
  • 1
  • 7
  • 23

1 Answers1

3

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)

Yurui Zhang
  • 2,230
  • 16
  • 16
  • Then I'm going to do it that way. Thanks. – Manuel Hoffmann Jan 16 '14 at 22:36
  • I found out that using the done() event instead of the success-callback doesn't pass the id of the object to the argument of the function (the Backbone-Id). But I need that id in my function. – Manuel Hoffmann Jan 18 '14 at 20:13
  • backbone passes the same arguments to the callbacks no matter if they are defined in the options hash or thru promises. Could you post your code to provide more details? – Yurui Zhang Jan 18 '14 at 20:33
  • I had a `this.user.fetch({ success: function(user) { console.log(user.id); } }).done(function(user) { console.log(user.id) });` First one shows "hakvdis988" (i made this value up). Second one shows "undefined". I think this is because the success-Callback passes the Backbone.Model (or something related) while the done()-Callback passes a normal javascript-object. – Manuel Hoffmann Jan 18 '14 at 20:51
  • I see. You probably should not use the params passed to your callback in this case. since you are fetching `this.user`, once it's done, backbone is gonna assign the correct attributes on this.user, you should be able to use `console.log(this.user.id)` in your callbacks as long as the context `this` is set correctly. – Yurui Zhang Jan 19 '14 at 22:29