gpt4 book ai didi

javascript - 删除使用绑定(bind)添加的事件监听器

转载 作者:IT老高 更新时间:2023-10-28 13:19:34 25 4
gpt4 key购买 nike

在 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);
};

})();

有没有更好的方法来做到这一点?

最佳答案

虽然@machineghost 说的是真的,但添加和删除事件的方式相同,但等式中缺少的部分是:

A new function reference is created after .bind() is called.

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 - 删除使用绑定(bind)添加的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com