[英]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.