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

tak*_*uya 148 javascript events bind listener

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

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

Ben*_*Ben 253

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

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

请参阅bind()更改函数引用吗?| 如何永久设置?

因此,要添加或删除它,请为变量分配引用:

var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);
Run Code Online (Sandbox Code Playgroud)

这对我来说是预期的.

  • 很好,这应该是公认的答案.感谢您更新旧主题,此主题在搜索引擎上排名第一,并且在您现在发布之前它没有正确的解决方案. (4认同)
  • 这对我有帮助——尽管这个答案是 4 年前发布的 :) (2认同)

Rai*_*gey 42

对于那些在向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() {
    // ...
  }
  
}
Run Code Online (Sandbox Code Playgroud)

  • 不错的伎俩,但React/Flux与什么有什么关系? (7认同)