删除通过绑定添加的事件侦听器

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

    };


})();

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


明月笑刀无情
浏览 359回答 3
3回答

千万里不及你

尽管@machineghost所说的是正确的,但事件的添加和删除方式相同,但等式中缺少的部分是:.bind()调用后会创建一个新的函数引用!请参见bind()是否会更改函数引用?| 如何永久设置?因此,要添加或删除它,请将引用分配给变量:var x = this.myListener.bind(this);Toolbox.addListener(window, 'scroll', x);Toolbox.removeListener(window, 'scroll', x);这对我来说是预期的。

胡说叔叔

对于那些在将React组件的侦听器注册到Flux存储中或从Flux存储中移除React侦听器时遇到此问题的人,请将以下行添加到组件的构造函数中:class App extends React.Component {  constructor(props){    super(props);    // it's a trick! needed in order to overcome the remove event listener    this.onChange = this.onChange.bind(this);    }  // then as regular...  componentDidMount (){    AppStore.addChangeListener(this.onChange);  }    componentWillUnmount (){    AppStore.removeChangeListener(this.onChange);  }  onChange () {    let state = AppStore.getState();    this.setState(state);  }    render() {    // ...  }  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript