Search code examples
javascriptjquerybackbone.jsbackbone-layout-manager

How can I fetch data asynchronously in backbone using backbone layout manager?


I'm having a problem in Layout Manager to get the view to wait to render until a bunch of AJAX calls have completed and successfully populated a collection which I pass to subviews.

Here's my initialization function:

initialize : function(){
            var collection;

            collection = new BobLawBlaw.Collection();
            collection.fetch();

            this.collection = collection;
        }

My fetch is a little complicated :

fetch : function(){
            var that = this;

            return $.when.apply(null, TL.reporting.getData.call(this, 125)).done(function(xhr1, xhr2){
                var data1 = xhr1[0].data, data2 = xhr2[0].data, dates = data1.date,

                // do a bunch of stuff with the data i get above to construct the models how i need
                models = [
                   // bunch of objects using the data
                ];

                that.add(models);
            });
        }

That getData function gathers the deferreds from TWO ajax calls and returns them in an array, thus allowing that done function to get triggered when both calls are done. This works as expected and I can get all the data I need.

However, the flow in the initialize function does not stop when that fetch is triggered, so the collection is not populated in time before LayoutManager goes on to beforeRender. How can I fetch asyncronously, but make the initialize function wait until both ajax calls complete AND populate the collection?


Solution

  • If you want to do it the Backbone way, yous should trigger a 'reset' event in your done callback. You then listen to this event in your view to launch the render function. Replacing the that.add( models ) with that.reset( models ) will add the models AND trigger the event for you.

    Then in the view's initialize function:

    // ...
    this.listenTo( collection, 'reset', this.render, this );
    

    And the this.render function will be called when the fetch is done.