我的頁面中有一段代表視圖的標記,以及與該視圖關聯的JS控制器函數。 (這些是Angular,但我不相信這個問題。)控制器代碼監聽從應用程序中其他地方觸發的自定義事件,並使用某些特定於控制器的邏輯處理該事件。無法解除綁定jQuery自定義事件處理程序
我的問題是控制器的事件處理程序被連接了太多次:每次重新激活視圖時都會連接,導致處理程序在每次自定義事件觸發時都會運行多次。我只希望處理程序在每個事件中運行一次。
我已經嘗試使用.off()
在綁定處理程序之前解除綁定處理程序;我試過.one()
以確保處理程序只運行一次;並且在閱讀其與.off()
here的相互作用之後我試過$.proxy()
。
這裏是我的代碼草圖:
// the code inside this controller is re-run every time its associated view is activated
function MyViewController() {
/* SNIP (lots of other controller code) */
function myCustomEventHandler() {
console.log('myCustomEventHandler has run');
// the code inside this handler requires the controller's scope
}
// Three variants of the same misbehaving event attachment logic follow:
// first attempt
$('body').off('myCustomEvent', myCustomEventHandler);
$('body').on('myCustomEvent', myCustomEventHandler);
// second attempt
$('body').one('myCustomEvent', myCustomEventHandler);
// third attempt
$('body').off('myCustomEvent', $.proxy(myCustomEventHandler, this));
$('body').on('myCustomEvent', $.proxy(myCustomEventHandler, this));
// all of these result in too many event attachments
};
// ...meanwhile, elsewhere in the app, this function is run after a certain user action
function MyEventSender() {
$('body').trigger('myCustomEvent');
console.log('myCustomEvent has been triggered');
};
點擊左右在我的應用程序切換到麻煩視圖五次,然後做它運行MyEventSender
動作後,我的控制檯看起來就像這樣:
myCustomEvent has been triggered
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
我怎樣才能得到它看起來像這樣:
myCustomEvent has been triggered
myCustomEventHandler has run
???
你可以讓你的控制器不做任何事情,如果它不可見?沒有修復你的bug,但它是一種解決問題的不同方式 – 2013-05-10 17:31:56
據我所知,Angular事件週期和jQuery事件週期完全不相關(除了它們都綁定到DOM之外)。您應該在'$(function(){...})'調用中將您的事件附加到控制器外部的
標記。 – rossipedia 2013-05-10 17:33:57適用於我:http://jsbin.com/adecul/1/edit – 2013-05-10 17:34:16