Is there a sexier way of doing the following:
scheduleSubjects.fetch({
success: function(){
subjectList.fetch({
success: function(){
assignments.fetch({
success: function(){
_this.render();
}
});
}
});
}
});
I want all the data to be retrieved before I start manipulating it.
Thanks.
Using JQuery's deferred objects, you can use $.when
to trigger a callback when multiple async calls have completed:
$.when(scheduleSubjects.fetch(), subjectList.fetch(), assignments.fetch()).then(_this.render);
Note that this works because JQuery.ajax
, and therefore also Backbone.fetch
, returns a deferred object.
An alternative to .then
is .done
, which passes you the parameters of the original callbacks (which you don't need in the OP, but you may in some cases):
$.when(scheduleSubjects.fetch(), subjectList.fetch(), assignments.fetch())
.done(function(scheduleSubjects, subjectList, assignments) {
_this.render();
})
);
var collections = [scheduleSubjects, subjectList, assignments];
var complete = _.invoke(collections, 'fetch');
$.when(null, complete).then(function(){
_this.render();
});
use Promises and Underscore's _.invoke()
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With