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.