相关疑难解决方法(0)

删除使用bind添加的事件侦听器

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

})();
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一方法就是跟踪每个添加了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);
    };

})();
Run Code Online (Sandbox Code Playgroud)

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

javascript events bind listener

148
推荐指数
2
解决办法
5万
查看次数

标签 统计

bind ×1

events ×1

javascript ×1

listener ×1