【问题标题】:How to remove event listener of a object with .bind(this)? [duplicate]如何使用 .bind(this) 删除对象的事件侦听器? [复制]
【发布时间】:2015-04-24 07:18:26
【问题描述】:

内部对象构造函数:

this.notification.addEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this));

当它破坏时:

this.notification.removeEventListener(barcodeScanner.NEW_READING, this.handleBarcode.bind(this), this);

我可以添加事件侦听器并正常工作,但我无法在对象销毁时删除单个事件侦听器。

虽然和问题关系不大,但是我用的是EventDispatcher.js和Class.js。

我可以修改 EventDispatcher.js 中的代码以满足我的需要。但是如何在不删除所有其他侦听器的情况下删除对象函数的事件侦听器?

【问题讨论】:

    标签: javascript event-handling dom-events


    【解决方案1】:

    这里是如何绑定取消绑定 事件处理程序一些组件强>:

    var o = {
      list: [1, 2, 3, 4],
      add: function () {
        var b = document.getElementsByTagName('body')[0];
        b.addEventListener('click', this._onClick());
    
      },
      remove: function () {
        var b = document.getElementsByTagName('body')[0];
        b.removeEventListener('click', this._onClick());
      },
      _onClick: function () {
        this.clickFn = this.clickFn || this._showLog.bind(this);
        return this.clickFn;
      },
      _showLog: function (e) {
        console.log('click', this.list, e);
      }
    };
    
    
    
    // Example to test the solution
    
    o.add();
    
    setTimeout(function () {
      console.log('setTimeout');
      o.remove();
    }, 5000);
    

    【讨论】:

      【解决方案2】:

      它没有被移除,因为它是一个不同的对象。

      .bind() 每次都返回一个新对象。

      您需要将其存储在某个地方并使用它来删除:

      var handler = this.handleBarcode.bind(this);
      

      然后

      this.notification.addEventListener(barcodeScanner.NEW_READING, handler);
      

      this.notification.removeEventListener(barcodeScanner.NEW_READING, handler);
      

      【讨论】:

      • 我将处理程序存储在对象属性中,但仍然无法成功删除它
      • @aokaddaoc:请提供一些“我将处理程序存储在对象属性中”的详细信息
      • 如果我必须使用处理程序发送参数,我该怎么做?谢谢
      猜你喜欢
      • 2012-09-10
      • 1970-01-01
      • 2019-07-22
      • 2018-01-25
      • 1970-01-01
      • 2018-09-04
      • 2011-05-22
      • 2010-10-10
      相关资源
      最近更新 更多