Javascript 如何使用.bind(this)删除对象的事件侦听器?
对象构造函数内部:Javascript 如何使用.bind(this)删除对象的事件侦听器?,javascript,javascript-events,event-handling,Javascript,Javascript Events,Event Handling,对象构造函数内部: this.notification.addEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this)); 当它破坏时: this.notification.removeEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this), this); 我可以添加事件监听器并正常工作,但当对象销毁时,我不能删除单个事
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);
然后
或
以下是如何在某些组件中绑定和解除绑定事件处理程序:
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);
我将处理程序存储在对象属性中,但仍然无法删除它successfully@aokaddaoc:请提供“我将处理程序存储在对象属性中”的一些详细信息如果我必须使用处理程序发送参数,我如何才能?谢谢
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);