Reputation: 43884
I have been looking into Jquery's promises through the use of when
and I am wondering if it is capable of fullfilling my scenario or whether I need to rethink how I am doing things.
So I have a backbone.js model with a couple of listeners in like:
this.on('supplier:change', function(){
$.get('/supplier_details', function(data){
// fill in some fields here
anotherAjaxCallInAnotherFunction();
});
});
anotherAjaxCallInAnotherFunction: function(){
// Another Ajax call
}
If I were to use when
like so model.set({supplier: 'ss'}).done();
would the promise be able to wait until the end of all Ajax calls?
What if I set multiple attributes that needed multiple Ajax calls within my backbone model? Would the promise encapsulate the entire setting of a model?
Upvotes: 0
Views: 211
Reputation: 43884
One thing I didn't realise until I actually tried this was that you CAN chain Ajaz calls in this way, you just need to be a bit creative with your coding.
The easiest way to chain these sort of calls is like so:
this.on('supplier:change', function(){
return $.get('/supplier_details').then(function(data){
return anotherAjaxCallInAnotherFunction();
});
}
function anotherAjaxCallInAnotherFunction(){
return $.ajax();
}
And just chaining the deferred object like this will allow you to not only make the calls async but also do it without locking the browser thread.
You can find more info here: http://api.jquery.com/jQuery.Deferred/
Upvotes: 1
Reputation: 1849
You could try:
$.when( firstAjaxCall, secondAjaxCall )
.done(
function(firstResp) { console.log(firstResp); },
function(secondResp) { console.log(secondResp); }
);
Or you could listenTo
a sync
event, and when successfully returned for firstAjaxCall
, you could call secondAjaxCall
: Backbone Events
"sync" (model, resp, options) — when a model (or collection) has been successfully synced with the server.
Upvotes: 0