2014-12-05 74 views
0

事件工作在附加鑑於骨幹事件不附加視圖

這裏不起作用是視圖的方法:

events: { 
    'click .toolbar_ship': 'openProfile' 
}, 
openProfile: function() { 
    gameView.$el.append(profileView.render().$el); 
} 

這裏簡介:

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.remove(); 
} 

在第一個配置文件被正確追加,並在點擊所有綁定工程很好,但是當我關閉配置文件,然後打開一個沒有任何點擊工作。

我什至不明白爲什麼它發生,我會感謝您的幫助。

這裏是點擊的例子:

$('.wrapGate').bind('click', function() { 
..... 
} 

謝謝)

+0

控制檯中是否有錯誤? – 2014-12-05 10:28:45

回答

1

您的問題來自實施的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刪除和事件解除綁定,當你不再需要它。

0

這是由於你的 「厄爾尼諾」 屬性,即烏爾追加應該是你EL

eg: el : "#container" // must set 

    <div id="container"> 
     . 
     . 
     . 
     . 
    <div id="new-appended-views"></div> 
    . 
    . 
    </div> 
內部視圖

這些事件將適用於所有新近添加的視圖