[英]Removing event listeners with anonymous function calls in JavaScript
我正在嘗試刪除所創建的 span 元素的事件偵聽器,其中調用的函數位於閉包內。 我嘗試了各種方法,但似乎都不起作用。
var MyClass = function () {}
MyClass.prototype.addSpan = function (el) {
var span = document.createElement('span');
span.innerHTML = "Text here";
el.appendChild(span);
span.addEventListener('click', (function (obj) {
return function () {
obj.removeSpan();
}
})(this), false);
}
MyClass.prototype.removeSpan = function () {
alert('removing span');
this.removeEventListener('click', arguments.callee, false);
// .... remove span ....
}
myclass = new MyClass();
myclass.addSpan(document.getElementById('box'));
我也用過
this.removeEventListener('click', (function (obj) {
return function () {
obj.removeSpan();
}
})(this), false);
代替this.removeEventListener('click', arguments.callee, false);
但沒有運氣。
任何幫助深表感謝!
var MyClass = function () {}
MyClass.prototype.listener=null;
MyClass.prototype.addSpan = function (el) {
var span = document.createElement('span');
span.innerHTML = "Text here";
el.appendChild(span);
span.addEventListener('click', (function (obj) {
return obj.listener = function () {
obj.removeSpan(this); // here 'this' refers to 'span'
}
})(this), false);
}
MyClass.prototype.removeSpan = function (el) {
alert('removing span');
el.removeEventListener('click', this.listener, false);
// .... remove span ....
}
myclass = new MyClass();
myclass.addSpan(document.getElementById('box'));
如果沒有偵聽器的引用,您將無法刪除它,因此我還在 MyClass 的原型中添加了一個屬性(偵聽器),然后將引用作為return obj.listener
,並且您還需要像 I' 一樣傳遞對象已經通過了obj.removeSpan(this);
在removeSpan
我收到了el
所以我可以完成el.removeEventListener
,希望它el.removeEventListener
幫助。
你也可以這樣做
var MyClass = function () {this.listener=null;}
代替
MyClass.prototype.listener=null;
這是一個例子。
嘗試將您的事件處理程序更改為此。
span.addEventListener('click', (function (obj) {
span.onclick = null;
return function () {
obj.removeSpan();
}
})(this), false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.