在JavaScript中,使用bind()删除作为事件侦听器添加的函数的最佳方法是什么?

示例

(function(){

    // constructor
    MyClass = function() {
        this.myButton = document.getElementById("myButtonID");
        this.myButton.addEventListener("click", this.clickListener.bind(this));
    };

    MyClass.prototype.clickListener = function(event) {
        console.log(this); // must be MyClass
    };

    // public method
    MyClass.prototype.disableButton = function() {
        this.myButton.removeEventListener("click", ___________);
    };

})();

我能想到的唯一方法是跟踪使用BIND添加的每个监听器.

使用此方法的上述示例:

(function(){

    // constructor
    MyClass = function() {
        this.myButton = document.getElementById("myButtonID");
        this.clickListenerBind = this.clickListener.bind(this);
        this.myButton.addEventListener("click", this.clickListenerBind);
    };

    MyClass.prototype.clickListener = function(event) {
        console.log(this); // must be MyClass
    };

    // public method
    MyClass.prototype.disableButton = function() {
        this.myButton.removeEventListener("click", this.clickListenerBind);
    };

})();

有更好的方法吗?

推荐答案

尽管@MachineHost所说的是真的,事件是以同样的方式添加和删除的,但等式中缺少的部分是:

调用.bind()后将创建一个新的函数引用.

Does bind() change the function reference? | How to set permanently?

因此,要添加或删除它,请将引用指定给一个变量:

var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);

这对我来说就像预期的那样.

Javascript相关问答推荐

为什么我的useDispatch挂钩在这里设置不正确?

在JavaScript中对大型级联数组进行切片的最有效方法?

useNavigation更改URL,但不呈现或显示组件

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

在Vite React库中添加子模块路径

如何用拉威尔惯性Vue依赖下拉?

为什么按钮会随浮动属性一起移动?

如何在 cypress 中使用静态嵌套循环

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

更改预请求脚本中重用的JSON主体变量- Postman

React.Development.js和未捕获的ReferenceError:未定义useState

Use Location位置成员在HashRouter内为空

如何使用TypeScrip设置唯一属性?

Google脚本数组映射函数横向输出

使用父标签中的Find函数查找元素

更新Redux存储中的对象数组

如何找到带有特定文本和测试ID的div?

Node.js错误: node 不可单击或不是元素

Pevent触发material 用户界面数据网格中的自动保存

使用createBrowserRoutVS BrowserRouter的Reaction路由