Phong Le
Phong Le

Reputation: 281

How do I handle with backbone rendering and ajax calls

So I have this dilemma, where I have a backbone view that creates a subviews that will be appended to the main view. Each of these subview have to make a ajax call that will retrieve data to complete the subview. Now the super view calls each subviews render and a appends it to itself. I then take the element of the main view and post it to a server, the problem is the ajax are finish after I sent the post to the server. Is there a better way to structure this work with asynchronous calls? I have this working with synchronous but the load bar doesn't even show up.

So here is example of what it is like:

WebView
generate:function(){
    var html = new MainView().render().el
    //ajax post to server with html
}

MainView 
    initalize:
    render:function(){
        this.el.append(new Subview().render().el);
    }

Subview
    initialize:
    render:fucntion(){
        //ajax - with  a success that alters the el
        return this;
    }

Now the generate function finishes before I can even get the data back from the calls and I cant bind to anything because the data is already sent to the server.

Upvotes: 0

Views: 394

Answers (1)

Selvaraj M A
Selvaraj M A

Reputation: 3136

MainView
childViews = [];
renderCompletedChildViews = 0;
addChildView: function () {
   var subView = new SubView();
   this.childViews.push(subView);
   subView.on("renderComplete", postToServer, this);
}
render: function () {
   for( var i=0; i<this.childViews.length; i++ ) {
        this.childViews[i].render(this.el);
   }
}
postToServer: function () {
   this.renderCompletedChildViews++;
   if( this.renderCompletedChildViews == this.childViews.length) {
       // Interact with server
   }
}


SubView
render: function (el) {
   // Make an ajax call, on receiving data append the data to el passed by parent view and trigger "renderComplete" on current instance
}

This way, you have made the code completely event driven and asynchronous.

Upvotes: 1

Related Questions