2012-03-14 71 views
5

我想弄清楚如何最好地移除使用jQuery的匿名事件處理程序。正確刪除匿名函數事件處理程序

我定義一個變量來保存我的jQuery對象:

var dom = $('#private-module'); 

後來在我的對象:

run: function() { 
    var button, that = this; 

    button = dom.append('<button class="btn">Click Me</button>'); 
    button.on('click', function(event) { 
     console.log('Clicked!'); 
     that.destroy(); 
    }); 
    }, 

    destroy: function() { 
    var button; 

    button = dom.find('.btn'); 
    button.off('click'); 
    } 

不管我做什麼,我不能殺的按鈕單擊處理程序。感覺像我對範圍的理解是有缺陷的。在這種情況下刪除處理程序的首選方法是什麼?我嘗試了命名空間的事件和各種各樣,但沒有運氣,所以我猜這是我忽略了一些簡單的東西。也許我甚至不應該爲事件處理程序使用匿名函數。

只是爲了螺栓上的東西,以我的推理使用.append:

http://jsperf.com/jquery-append-vs-appendto

下面是最終的解決方案:

dom.append('<button class="btn">Send Message</button>'); 
button = dom.find('.btn'); 
button.on('click', function (event) { 
    sendTestMessage(); 
    that.destroy(); 
}); 

我也同意,並且要了解使用方法。一。感謝那。

+1

其實你應該使用'one'功能這一點。 – noob 2012-03-14 10:33:21

回答

7
button = dom.append('<button class="btn">Click Me</button>'); 

返回dom,而不是按鈕,所以你綁定了事件處理函數dom

更改爲:

button = $('<button class="btn">Click Me</button>').appendTo(dom); 

這裏是working demo

+0

感謝您的解釋和工作示例。對我完全意義。 – backdesk 2012-03-14 12:06:16

1

問題是buttondom,而不是.btn

button = dom.append('<button class="btn">Click Me</button>'); 

//a console.log(button) here reveals that button is "dom" 

//and thus you are adding a handler to "dom 
button.on('click', function(event) { 
    console.log('Clicked!'); 
    that.destroy(); 
}); 

一個辦法做到這一點得益於.on()代表團權力是添加元素的子選擇您想要的處理程序綁定第二個參數。

button.on('click', '.btn' function(event) { 
    //the value of "this" in here is the ".btn" 
    console.log('Clicked!'); 
    that.destroy(); 
}); 

破壞,我們使用.off()與有關.btn第二個參數:

button.off('click', '.btn'); 
+0

謝謝約瑟夫。你提供的例子似乎並不適合我,也許我錯誤輸入了一些東西。請參閱上文以瞭解我所解決的問題。 – backdesk 2012-03-14 12:10:29