Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i sync two Backbone fetch calls with JQuery WHEN and THEN

i found out a cool thing in jquery: you can do:

$.when([$.get(..), $.ajax(...), $.getJSON(...)]).then(function(data1,data2,data3){
         // code to run when all requests are done
        });

this is great when you want to sync many ajax calls.

in backbone an ajax call is being issued every time you fetch a model or collection:

cardsCollection.fetch();

my question is how can i achieve similar syncing capabilities with backbone model/collection fetching:

i would like to do something like:

$.when([series.fetch(), cardsCollection.fetch()]).then(function(){
            cardsListView.seriesID = seriesID;
            cardsListView.seriesName = series.get('seriesName');
            cardsListView.template = _.template(CardsListTemplate);
            cardsListView.render();
            $('#loader').hide();
        });

is it possible?

tnx. ;-)

like image 327
Guy Avatar asked Dec 26 '22 23:12

Guy


2 Answers

Yes, it's possible. Just pass several Deferred to jQuery.when: $.when(series.fetch(), cardsCollection.fetch()).then(...)

like image 113
theotheo Avatar answered Dec 29 '22 11:12

theotheo


$.when does not accept an array, you would need to use .apply with $.when.

$.when.apply($,[series.fetch(), cardsCollection.fetch()]).done(dostuff);

However, series.fetch() and cardsCollection.fetch() would have to return deferred objects.

If you don't use .apply, it will resolve instantly because you didn't give it a deferred object.

like image 35
Kevin B Avatar answered Dec 29 '22 13:12

Kevin B