使用Javascript删除事件侦听器

时间:2016-07-07 12:39:34

标签: javascript

我想使用Javascript删除事件监听器,但它似乎无效......

我的代码不起作用:

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

2 个答案:

答案 0 :(得分:1)

.bind()会创建一个副本,因此当您使用.removeEventListener时,实际上是在传递另一个引用。

你有2个approches:

1)您可以存储绑定功能:

this.show = show.bind(this);

然后使用它:

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

2)将这些功能添加到this原型:

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

答案 1 :(得分:0)

当您调用show.bind(this)时,这会有效地创建一个新功能。所以当你写:

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

这增加了一个函数(让我们称之为函数A)

当你写

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

这将删除不同的功能(功能B)。

您需要存储引用并添加和删除相同的功能才能使其生效。