所以我有一個非常簡單的骨幹應用程序模型,集合和一些意見。我通過在頁面加載時執行collection.fetch()來從服務器獲取實際數據。如何將事件綁定到尚未加載的模型?
我的問題是我的一個視圖是一個「細節」視圖,我想將它綁定到一個特定的模型 - 但是當頁面加載時我還沒有模型。我的代碼看上去是這樣的:
window.App = {
Models: {},
Collections: {},
Views: {},
Routers: {}
}
App.Models.Person = Backbone.Model.extend({
urlRoot: '/api/people'
});
App.Collections.People = Backbone.Collection.extend({
model: App.Models.Person,
url: '/api/people'
});
people = new App.Collections.People()
App.Views.List = Backbone.View.extend({
initialize: function() {
this.collection.bind('reset', this.render());
},
render: function() {
$(this.el).html("We've got " + this.collection.length + " models.")
}
});
listView = new App.Views.List({collection: people})
App.Views.Detail = Backbone.View.extend({
initialize: function() {
this.model.bind('change', this.render());
},
render: function() {
$(this.el).html("Model goes here!")
}
});
App.Routers.Main = Backbone.Router.extend({
routes: {
'/people': 'list',
'/people/:id': 'detail'
},
list: function() {
listView.render();
},
detail: function(id) {
detailView = new App.Views.Detail({model: people.get(id)})
detailView.render()
}
})
main = new App.Routers.Main();
Backbone.history.start();
people.fetch();
但是,如果我開始與詳細的路線活躍,people
集合是空的,所以people.get(id)
不返回任何東西,所以我的新視圖this.model
不確定,並榮獲」我不能讓任何與它有關的事件發生。錯誤是:
Uncaught TypeError: Cannot call method 'bind' of undefined
如果我用列表的路線開始活躍,那麼到時候我點擊一個項目,彈出詳細視圖填充people
,所以一切正常。
在頁面加載後獲取數據時,爲「細節」視圖綁定模型相關事件的正確方法是什麼?