我正在使用backbone.js處理項目,並且我面臨的問題是我有一個不需要與服務器同步的模型,模型只是爲了獲取用戶數據來初始化其餘的視圖,它是一種附加模型的應用程序的包裝視圖。如何從多個網址獲取模型時渲染視圖
這個模型從多個urls中獲取數據,而我的實際問題是視圖在所有數據被分配給模型之前進行渲染,而在其他情況下,當所有的數據已經分配給模型。
我正在使用$ .when()來獲取模型並調用.done()來呈現視圖,但我想我不理解延遲對象的概念。想知道你們爲了解決這個問題而提出什麼樣的建議。我給你留下一個關於我的代碼如何的例子。
型號
var userModel = Backbone.Model.extend({
url: "/api/vacationtypes.json",
defaults: {
userName: 'anonymous',
availableDays: 0,
vacationType: []
},
initialize: function() {
var that = this;
_.bindAll(this,'parseAvailableDays');
},
parse: function(data){
return {vacationType: data.data}
},
getAvailableDays: function() {
$.ajax({
url: "/api/staffAvailableDays/get/" + Zvacations.session.email + ".json",
success: this.parseAvailableDays
});
},
parseAvailableDays: function(response) {
this.set('availableDays', response.data[0].availableDays);
}
});
查看
var Home = Backbone.View.extend({
tagName: "section",
className: "home",
el: "#request-form"
events: {
// events for the view
},
initialize: function(){
var that = this;
this.setPageTitle('Home');
this.model.on('change:availableDays', this.render, this);
// once all fetches for model are done render the view (sometime execute before the succes of getAvailableDays)
$.when(this.model.fetch(), this.model.getAvailableDays()).done(function(){
that.render();
});
},
render: function(){
var template = _.template(homeViewTemplate, this.model.toJSON());
this.$el.html(template);
// get holydays from db
this.getHolidays();
//assign total steps after render
this.totalSteps = $(homeViewTemplate).find('fieldset').length
// initialize jQuery UI datepicker
this.dateSelectorView();
return this;
},
// here goes rest of the view methods
});
希望你們能幫助我找出哪一個是等待,直到全部取做是爲了呈現最好的方式。
這就是問題所在,我不明白jqXHR的返回是需要的,非常感謝您的幫助,一切都完美無缺! – 2014-10-01 20:24:57