0
我正在开发骨干js应用程序,并且我坚持呈现需要从四个XHR请求中获取数据的视图。我做了如下的事情来达到这个目的:呈现骨干视图之前的多个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()
}));
}
});
上面的代码有效,但不是最好的方法,因为它执行一次成功获取而不是并行。什么是在所有提取请求完成后异步执行多个提取请求并呈现查看的最佳方法?
对不起,我的英语不好。
一个经典的问题,有很多原因和解决方案(又名“地狱回调”)。你确定你同时需要“承诺”的结果吗?难道你不能分裂你的观点(结果似乎并不相互依赖)?或者添加另一个控制器端点来将活动和myactivities返回成一堆? – matthias
这可能有所帮助:http://stackoverflow.com/questions/4368946/javascript-callback-for-multiple-ajax-calls – Hazaart
@matthias:我已经将我的视图分为两部分,并且分割视图需要四个获取请求。我对骨干js是新手,我有点不知道在这种情况下该怎么做。 – Raeesaa