我有一个标记,在我的JS应用程序中的某个点上,它会得到一个click eventListener。并且意外地在时间上进一步获得第二点击事件监听器。我希望首先删除第一个,然后再添加它。
我如何使用chrome dev工具来确定事件侦听器何时被添加、删除,以及哪些代码导致了事件侦听,包括调用堆栈?
我尝试了控制台日志记录的东西,但我仍然看不到原因。
监听器的添加和删除是在这样的函数中完成的
class SomeClass {
/**
* Enables listeners so that clicking on the navigatableElement can work.
*/
enableListeners() {
this.disableListeners();
this._navigatableElement.addEventListener('click', this._clickEventHandler.bind(this));
}
/**
* Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
*/
disableListeners() {
this._navigatableElement.removeEventListener('click', this._clickEventHandler.bind(this));
}
}发布于 2019-05-31 17:20:06
一种可用于调试(但不是在生产代码中)的可能方法是写入Element.prototype.addEventListener,允许您在调用它时记录和console.trace:
const { addEventListener, removeEventListener } = EventTarget.prototype;
Element.prototype.addEventListener = function(...args) {
console.log('Adding event listener!', this, args);
console.trace();
// debugger
return addEventListener.apply(this, args);
};
Element.prototype.removeEventListener = function(...args) {
console.log('Removing event listener!', this, args);
console.trace();
// debugger
return removeEventListener.apply(this, args);
};
console.log('real script start');
const fn = () => console.log('fn');
foo.addEventListener('click', fn);
console.log('listener added.');
foo.removeEventListener('click', fn);<div id="foo">
</div>
您的特定代码无法工作,因为每次执行.bind时,您都会创建一个新函数。您可以在构造函数中使用绑定的公共React模式,这样每个对this._clickEventHandler的引用都将指向相同的函数。(需要使用与addEventListener完全相同的函数引用来调用removeEventListener才能工作。)
class SomeClass {
constructor() {
this._clickEventHandler = this._clickEventHandler.bind(this);
}
/**
* Enables listeners so that clicking on the navigatableElement can work.
*/
enableListeners() {
this.disableListeners();
this._navigatableElement.addEventListener('click', this._clickEventHandler);
}
/**
* Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
*/
disableListeners() {
this._navigatableElement.removeEventListener('click', this._clickEventHandler);
}
}发布于 2019-05-31 17:15:04
您的删除代码不起作用,因为每次调用.bind()都会生成一个新的函数对象。您正在请求删除一个监听程序,而浏览器并未将其视为已注册的监听程序,它会忽略该调用。
https://stackoverflow.com/questions/56392058
复制相似问题