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