我正在开发一个骨干js应用程序,我不得不渲染一个需要从四个XHR请求中获取数据的视图。我做了类似下面的事情来实现这个目标:
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()
}));
}
});
上面的代码可以工作,但这不是最好的方法,因为它在其他成功执行一次获取而不是并行执行。在所有获取请求完成后,异步执行多个获取请求并呈现视图的最佳方法是什么?
抱歉我的英语不好。
答案 0 :(得分:0)
我从answer到另一个SO问题的解决方案建议使用jQuery.when作为:
$.when(
this.trip.fetch(),
this.activities.fetch(),
this.myactivities.fetch(),
this.user.fetch()
).then(function() {
that.render(); //that represents view over here
});