【发布时间】:2019-03-27 15:46:32
【问题描述】:
在我的 JS 模块中,我有一个添加几个事件监听器的函数
clickCatcher.addEventListener("click", this.clickCatcherFunction);
window.addEventListener('resize', this.clickCatcherFunction);
document.addEventListener('keydown', this.clickCatcherFunction);
并且调用了函数clickCatcherFunction,到目前为止一切都很好。现在是时候删除所有事件侦听器(如果其中一个触发了)。
document.removeEventListener('keydown', this.clickCatcherFunction);
没有错误,但事件侦听器仍处于活动状态。如何访问我传入的相同功能?在侦听器函数内部, this.someOtherFunc 也失败了。这个监听器的范围是什么,它有变化吗?
编辑。为上下文添加更多内容:
export default class Hints {
constructor(){
//ref for adding and removing
this.clickCatcherFunction = this.clickCatcherFunction.bind(this);
//add invisible top div to catch click and remove hint,
const clickCatcher = document.createElement("div");
clickCatcher.id = "clickCatcher";
document.body.appendChild(clickCatcher);
clickCatcher.addEventListener('click', this.clickCatcherFunction);
window.addEventListener('resize', this.clickCatcherFunction);
document.addEventListener('keydown', this.clickCatcherFunction);
}
clickCatcherFunction() {
//clickCatcher gets deleted from the dom
document.removeEventListener('keydown', this.clickCatcherFunction);
window.removeEventListener('resize', this.clickCatcherFunction);
}
}
//in the JS that imported Hints.JS
import Hints from "../Hints.js"
let hint = new Hints();
将解决方案添加到构造函数中。
【问题讨论】:
-
如果
clickCatcherFunction()是全局的,它会起作用;但前提是所有的 add 和 remove 调用也发生在全局上下文中。 -
使用
that=this技巧,或 bind() 你的回调来获得正确的参考。 -
es6 classes and "this" with event handlers 的重复项(不幸的是,我的 Mjölnir 已经在以前版本的问题中打破了......)
标签: javascript addeventlistener