Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone multiple collection fetch

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.

like image 982
Ilya Karnaukhov Avatar asked Oct 21 '13 19:10

Ilya Karnaukhov


2 Answers

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();
    })
);
like image 113
McGarnagle Avatar answered Sep 21 '22 15:09

McGarnagle


var collections = [scheduleSubjects, subjectList, assignments];
var complete = _.invoke(collections, 'fetch');

$.when(null, complete).then(function(){
    _this.render();
});

use Promises and Underscore's _.invoke()!

like image 25
benhowdle89 Avatar answered Sep 21 '22 15:09

benhowdle89