0

I am developing a backbone js application and I am stuck at rendering a view which requires data fetched from four XHR requests. I have done something like below to achieve this:

app.ItineraryLeftView = Backbone.View.extend({

el: '.page',

events: {
},

tpl: Handlebars.compile(
  document.getElementById('my-template').innerHTML
),


initialize: function() {
  app.View = this;
  var that=this;

  this.trip=new app.Trip();

  this.trip.fetch({
    success: function (trip) {
      that.activities=new app.Activities(); 
      that.activities.fetch({
        success: function (activities) {
          that.myactivities=new app.MyActivities(); 
          that.myactivities.fetch({
            success: function (myactivities) {
              that.user = new app.User(); 
              that.listenTo(that.user, 'sync', that.render, that); 
              that.user.fetch();
            }
          });
        }
      });          
    }
  });     
},
render: function () {

  this.$el.html( this.tpl({
    trip: this.trip.toJSON(),
    activities: this.activities.toJSON(),
    myactivities: this.myactivities.toJSON(),
    user: this.user.toJSON()
  }));
}

});

The above code works but it is not best approach to do so as it executes one fetch on success of other and not in parallel. What is the best approach to execute multiple fetch requests asynchronously and render view after all fetch requests has been completed?

Sorry for my bad english.

Raeesaa
  • 3,267
  • 2
  • 22
  • 44
  • A classic problem with many reasons and solutions (aka "callback hell"). Are you sure you need both results "promised" at once? Couldn't you split up your view (results don't seem to depend on each other)? Or add another controller endpoint to return activities and myactivities in one bunch? – matthias May 19 '14 at 09:26
  • This might help: http://stackoverflow.com/questions/4368946/javascript-callback-for-multiple-ajax-calls – Anonymoose May 19 '14 at 09:27
  • @matthias: I have already divided my view into two sections and divided view requires four fetch requests. I am new to backbone js and I kind of don't know what to do in such situation. – Raeesaa May 19 '14 at 09:33
  • 1
    Have you looked at [JavaScript Promises](http://www.html5rocks.com/en/tutorials/es6/promises/)? – Xan May 19 '14 at 09:42
  • @Xan: No. I'll have a look at it. Thanks! – Raeesaa May 19 '14 at 09:53

1 Answers1

0

I got solution from an answer to another SO question which suggests using jQuery.when as:

$.when(
    this.trip.fetch(),
    this.activities.fetch(),
    this.myactivities.fetch(),
    this.user.fetch()
  ).then(function() {
    that.render(); //that represents view over here
  });
Community
  • 1
  • 1
Raeesaa
  • 3,267
  • 2
  • 22
  • 44