【问题标题】:trouble removing EventListeners from the listener从侦听器中删除 EventListener 时遇到问题
【发布时间】: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


【解决方案1】:

在添加时,您每次拨打电话都需要拨打.removeEventListener

所以从你的代码:

clickCatcher.removeEventListener('click', this.clickCatcherFunction);
window.removeEventListener('resize', this.clickCatcherFunction);
document.removeEventListener('keydown', this.clickCatcherFunction);

请注意,我会小心指向 this 的方式。 this 将是您正在调用的上下文的封闭对象。这可能不是你想要的。

根据您的编辑:

document.addEventListener('keydown', this.clickCatcherFunction.bind(this));

会有所帮助。

【讨论】:

  • 使用 .bind(this) 和 addEventListener 使该函数能够通过 this.other 引用其他函数。但没有从窗口或文档中删除事件监听器。但是如果我在构造函数中放一个 this.listener = this.listener.bind(this) ,我可以用它来添加和删除。
  • 是的,因为 .bind 返回一个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多