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

tom*_*271 3 javascript event-handling javascript-events

内部对象构造函数:

this.notification.addEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this));
Run Code Online (Sandbox Code Playgroud)

当它失败时:

this.notification.removeEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this), this);
Run Code Online (Sandbox Code Playgroud)

我可以添加事件监听器并正常工作,但是当对象销毁时我无法删除单个事件监听器.

虽然它与问题没有多大关系,但我使用的是EventDispatcher.js和Class.js.

我可以修改EventDispatcher.js中的代码以满足我的需要.但是如何在不删除所有其他侦听器的情况下删除objcet函数的事件侦听器?

zer*_*kms 9

它没有被删除,因为它是一个不同的对象.

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

您需要将其存储在某处并使用它来删除:

var handler = this.handleBarcode.bind(this);
Run Code Online (Sandbox Code Playgroud)

然后

this.notification.addEventListener(barcodeScanner.NEW_READING, handler);
Run Code Online (Sandbox Code Playgroud)

要么

this.notification.removeEventListener(barcodeScanner.NEW_READING, handler);
Run Code Online (Sandbox Code Playgroud)

  • 我将处理程序存储在object属性中,但我仍然无法成功删除它 (2认同)