在JavaScript中删除事件列表器

时间:2015-12-11 16:47:59

标签: javascript html5

我在JavaScript中创建了一个类,它在启动类时执行与特定任务相关的键调用(按键)。

Class有一个函数'receaveKey',它由addEventListener引用,就像这个

一样
 document.addEventListener("keypress",this.receaveKey.bind(this));

这适合我,但我的班级有另一个功能“退出” 当这个被调用时我想删除那个事件监听器,我尝试了这个但是确实有效。

document.removeEventListener("keypress",this.receaveKey.bind(this));

注意: - 我也尝试了这个但是有问题我无法提供类的启动对象的引用,因为当使用类的'函数'按键时我也必须做一些任务。

document.addEventListener("keypress",staticClassReceaveKey);

document.removeEventListener("keypress",staticClassReceaveKey);

注意: - 我也试过这个

document.addEventListener("keypress",this.receaveKey);

    document.removeEventListener("keypress",this.receaveKey);

但是当使用类的方法作为参考函数时,没有找到任何运气,因为没有删除监听器

3 个答案:

答案 0 :(得分:5)

您必须删除自己添加的相同功能,但bind始终会返回功能。

所以你必须记住第一个,然后在删除时使用它:

this.boundReceaveKey = this.receaveKey.bind(this);
document.addEventListener("keypress",this.boundReceaveKey);

// ...later...
document.removeEventListener("keypress",this.boundReceaveKey);
this.boundReceaveKey = undefined; // If you don't need it anymore

旁注:拼写是“接收”。

您要求的例子:

function Thingy(name) {
  this.name = name;
  this.element = document.getElementById("the-button");
  this.bindEvents();
}
Thingy.prototype.bindEvents = function() {
  if (!this.boundReceiveClick) {
    this.boundReceiveClick = this.receiveClick.bind(this);
    this.element.addEventListener("click", this.boundReceiveClick, false);
  }
};
Thingy.prototype.unbindEvents = function() {
  if (this.boundReceiveClick) {
    this.element.removeEventListener("click", this.boundReceiveClick, false);
    this.boundReceiveClick = undefined;
  }
};
Thingy.prototype.receiveClick = function() {
  var p = document.createElement("p");
  p.innerHTML = "Click received, name = " + this.name;
  document.body.appendChild(p);
};

var t = new Thingy("thingy");
t.bindEvents();

document.getElementById("the-checkbox").addEventListener("click", function() {
  if (this.checked) {
    t.bindEvents();
  } else {
    t.unbindEvents();
  }
}, false);
<input id="the-button" type="button" value="Click me">
<br><label><input id="the-checkbox" type="checkbox" checked> Bound, when this is unchecked the button won't do anything</label>

答案 1 :(得分:3)

.bind返回一个带有上下文绑定的新函数。

您需要传递一个函数引用,然后才能将其作为acallback删除。

var boundFn = this.receiveKey.bind( this )
element.addEventListener( 'keypress', boundFn )
element.removeEventListener( 'keypress', boundFn )

答案 2 :(得分:1)

.bind创建了一个新功能。

你可以做到

this.receaveKey = function() {}.bind(this)
相关问题