如何移除使用.bind(this)绑定的对象的事件监听器?

4

对象构造函数内部:

this.notification.addEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this));

而当它被销毁:

this.notification.removeEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this), this);

我可以添加事件监听器并且可以正常工作,但是当对象销毁时,我无法删除单个事件监听器。
虽然这与问题不太相关,但我正在使用EventDispatcher.js和Class.js。
我可以修改EventDispatcher.js中的代码来符合我的需求。但是如何在不删除所有其他监听器的情况下删除对象函数的事件监听器?
2个回答

11

之所以没有被移除是因为它是一个不同的对象。

.bind()每次都会返回一个新对象。

你需要将其存储在某个地方并使用它来删除:

var handler = this.handleBarcode.bind(this);

然后

this.notification.addEventListener(barcodeScanner.NEW_READING, handler);
或者
this.notification.removeEventListener(barcodeScanner.NEW_READING, handler);

2
我将处理程序存储在对象属性中,但仍然无法成功删除它。 - tom10271
@aokaddaoc:请提供“我将处理程序存储在对象属性中”的一些细节。 - zerkms
如果我需要使用处理程序发送参数,我该怎么做?谢谢。 - Alberto Acuña

1
以下是需要翻译的内容:

这里是如何在某个组件中绑定和解除事件处理程序的方法:

var o = {
  list: [1, 2, 3, 4],
  add: function () {
    var b = document.getElementsByTagName('body')[0];
    b.addEventListener('click', this._onClick());

  },
  remove: function () {
    var b = document.getElementsByTagName('body')[0];
    b.removeEventListener('click', this._onClick());
  },
  _onClick: function () {
    this.clickFn = this.clickFn || this._showLog.bind(this);
    return this.clickFn;
  },
  _showLog: function (e) {
    console.log('click', this.list, e);
  }
};



// Example to test the solution

o.add();

setTimeout(function () {
  console.log('setTimeout');
  o.remove();
}, 5000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接