Search code examples
jqueryajaxbackbone.jscallback

Backbone's success callback called before jquery's ajaxSuccess


I would like to make sure that jQuery's ajaxSuccess callback is called before Backbone's success, which is not the case in my experience. I would like this

someModel.fetch({ success: function() {
  console.log('2');
} });

$(document).ajaxSuccess(function(event, xhr, ajaxOptions) {
  console.log('1');
});

to log 1, 2 and not 2, 1. The reason being that I am using ajaxSuccess to pre-filter the response and saving data that are needed in Backbone's callback


Solution

  • what you have shown not necessarily mean Backbone call is earlier than ajax success callback. it is probably ajax success is called first. then immediately the backbone callback is also invoked. then it depends on which one is faster, the faster one will log first.

    it means backbone callback is not called after ajaxsuccess is finished.

    in your case, you want to preprocess ajax stuff before passing into model. this is very common. in fact, Backbone does have a native support of this. check Backbone.parse method. it is by default empty, but you can certainly modify it to change the response.