如何使用.bind(this)删除对象的事件侦听器

How to remove event listener of a object with .bind(this)?

本文关键字:对象 事件 侦听器 删除 何使用 bind this      更新时间:2024-03-06

内部对象构造函数:

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中修改代码以满足我的需要。但是,如何在不删除所有其他侦听器的情况下删除对象函数的事件侦听器?

它不会被删除,因为它是一个不同的对象。

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

你需要把它存储在某个地方,然后用它来删除:

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

然后

this.notification.addEventListener(barcodeScanner.NEW_READING, handler);

this.notification.removeEventListener(barcodeScanner.NEW_READING, handler);

以下是如何在某些组件绑定解除绑定事件处理程序的方法:

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