简体   繁体   中英

Remove event listeners using Javascript

I'd like to remove event listeners using Javascript but it seems not working...

My code that not works :

function add () {
  var container = this.container;
  var span = document.createElement('span');
  span.classList.add('tooltip');
  span.innerHTML = this.msg;
  container.appendChild(span);
  this.tooltip = span;
  this.inputString.input.addEventListener('mouseenter', show.bind(this));
  this.inputString.input.addEventListener('mouseout', hide.bind(this));
}

function remove() {
  if (this.container.getElementsByClassName('tooltip').length) {
    this.inputString.input.removeEventListener('mouseenter', show);
    this.inputString.input.removeEventListener('mouseout', hide);
    this.container.removeChild(this.tooltip);
    this.msg = null;
    this.inputString = null;
    this.container = null;
    this.tooltip = null;
  }
}

function show () {
  var container = this.container,
      mainElmt = this.inputString.mainElmt,
      tooltip = this.tooltip;
  if ((container.offsetWidth - (mainElmt.offsetLeft + mainElmt.offsetWidth)) < ($(tooltip).outerWidth() + 5)) {
    tooltip.style.left = parseInt(mainElmt.style.left || getComputedStyle(this.inputString.el).left, 10) - ($(tooltip).outerWidth() + 5) + 'px';
    tooltip.classList.add('is-on-right');
  } else {
    tooltip.style.left = parseInt(mainElmt.style.left || getComputedStyle(this.inputString.el).left, 10) + parseInt(mainElmt.style.width || this.inputString.el.style.width, 10) + 5 + 'px';
    tooltip.classList.add('is-on-left');
  }
  tooltip.style.top = parseInt(mainElmt.style.top || getComputedStyle(this.inputString.el).top, 10) - 15 + (parseInt(mainElmt.style.height || this.inputString.el.style.height, 10) / 2) + 'px';
  tooltip.style.display = 'block';
}

.bind() creates a copy, so when you use .removeEventListener you are actually passing another reference.

You have 2 approches:

1) you can store the bound function:

this.show = show.bind(this);

and then use it:

.addEventListener('...', this.show);
.removeEventListener('...', this.show);

2) add these functions to this prototype:

// Assuming that `this` is an instance of function MyClass() {}
MyClass.prototype.show = function show() {...}

When you invoke show.bind(this) this effectively creates a new function. So when you write:

this.inputString.input.addEventListener('mouseenter', show.bind(this));

This adds one function (let's call it function A)

and when you write

this.inputString.input.removeEventListener('mouseenter', show.bind(this));

this removes a different function (function B).

You need to store a reference and add and remove the same function in order for this to work.

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