为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2019-12-17 14:54:21
在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);    };})();有没有更好的方法可以做到这一点?
查看完整描述

3 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

尽管@machineghost所说的是正确的,但事件的添加和删除方式相同,但等式中缺少的部分是:


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


请参见bind()是否会更改函数引用?| 如何永久设置?


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


var x = this.myListener.bind(this);

Toolbox.addListener(window, 'scroll', x);

Toolbox.removeListener(window, 'scroll', x);

这对我来说是预期的。


查看完整回答
反对 回复 2019-12-17
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

对于那些在将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() {

    // ...

  }

  

}


查看完整回答
反对 回复 2019-12-17
  • 3 回答
  • 0 关注
  • 358 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号