简体   繁体   中英

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

eg:

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();

How would I create a method that would remove the listener from the element?

Why would you want to keep the anonymous function?

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);
}

Also, be careful with addEventListener()/removeEventListener() since they are DOM Level 2 standards based - something IE doesn't do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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