2012-10-19 81 views
3

有沒有辦法刪除骨幹視圖實例化的所有事件偵聽?例如,假設我有以下HTML/JavaScript。當點擊#box時,我想要一個彈出窗口來打招呼。刪除骨幹視圖的所有事件偵聽器

<div id="box" style="height: 100px; width: 100px; background-color: red"></div> 

var Listener = Backbone.View.extend({ 
    el: "#box", 
    events: { 
     'click #box' : 'hello' 
    }, 
    hello: function() { 
     alert('hello!'); 
    } 
}) 

var listener = new Listener(); 

現在,我想要刪除事件監聽器。將監聽器設置爲其他內容不起作用:

listener = ''; // doesn't work 

如何刪除事件偵聽器?

+1

可能是你可以看一下[文章](http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps /)[Derick Bailey](http://lostechies.com/derickbailey/author/derickbailey/)。 – Cyclone

回答

14

任何地方在您的視圖:

this.undelegateEvents(); 

然後,您可以手動在稍後時間重新綁定事件與delegateEvents();

我用添加的方法到Backbone.View原型爲ea甲硅烷清理的觀點:

Backbone.View.prototype.close = function() { 
    this.undelegateEvents(); 
    this.remove(); 
} 

// internal usage 
this.close(); 

// external usage 
myView.close(); 

EDIT 19/07/2013

骨幹v0.9.9加入.listenTo()方法的觀點,因此很容易解除綁定外部事件視圖時除去。

你可以在這裏閱讀更多: