繁体   English   中英

Javascript:删除事件侦听器,该事件侦听器带有与对象方法相关的匿名函数

[英]Javascript: removing an event listener attached with an anonymous function to an object's method

例如:

function myclass (htmlelement) {
  this.element = htmlelement;
}

myclass.prototype.hoverfunc = function() {
  alert (this.element.id);
}

myclass.prototype.doListen = function() {
  this.element.addEventListener ('mouseover', function() {this.hoverfunc();}.bind(this),false);
}

elListen = new myclass (document.getElementById('foo'));
elListen.doListen();

我将如何创建一种方法,该方法将从元素中删除侦听器?

您为什么要保留匿名功能?

myclass.prototype.doListen = function() {
  this.listener = function() {this.hoverfunc();}.bind(this);
  this.element.addEventListener ('mouseover', this.listener, false);
}


myclass.prototype.stopListen = function() {
  this.element.removeEventListener('mouseover', this.listener);
}

另外,请谨慎使用addEventListener()/removeEventListener()因为它们是基于DOM 2级标准的-IE不会这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM