您的問題來自實施的openProfile
方法。
您正在使用的profileView
有實例,你在什麼地方初始化像
var profileView = new ProfileView();
ProfileView
延伸從Backbone.View
,當你初始化它會delegate events 並將其綁定到this.$el
。
當您在this.$el
上調用jQuery的remove()
方法時,它會將其刪除並解除所有連接事件的綁定。
下一次當你打電話給openProfile
時,profileView.render().$el
會返回你的看法,但沒有任何事件。
爲了避免這種情況,您需要重構代碼。有幾種情況可以實現此任務。其中之一是始終使用的ProfileView
新實例,如:
events: {
'click .toolbar_ship': 'openProfile'
},
openProfile: function() {
var profileView = new ProfileView();
gameView.$el.append(profileView.render().$el);
}
和ProfileView:
events: {
'click .object_in_inventory': 'inventoryClick',
'click .object_in_cell': 'cellClick',
'click .close_profile': 'closeProfile'
},
render: function() {
this.$el.html(this.template());
return this;
},
closeProfile: function() {
this.remove(); // this.remove() is the method of Backbone.View, which will manage removing of view and unbinding of events.
}
另一種解決方案可以只隱藏個人資料視圖當關閉個人
用戶點擊
events: {
'click .toolbar_ship': 'openProfile'
},
openProfile: function() {
if (this.profileView) {
this.profileView.$el.show(); // your custom showing logic
} else {
this.profileView = new ProfileView(); // caching profileView
gameView.$el.append(profileView.render().$el);
}
}
and ProfileView中:
events: {
'click .object_in_inventory': 'inventoryClick',
'click .object_in_cell': 'cellClick',
'click .close_profile': 'closeProfile'
},
render: function() {
this.$el.html(this.template());
return this;
},
closeProfile: function() {
this.$el.hide(); // your custom showing logic
}
不要忘記管理ProfileView刪除和事件解除綁定,當你不再需要它。
控制檯中是否有錯誤? – 2014-12-05 10:28:45