4

Inside object constructor:

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

And when it destroys:

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

I can add event listener and works properly but I cannot remove single event listener when object destroys.

Although it is not quite related to the problem, I am using EventDispatcher.js and Class.js.

I can modify code in EventDispatcher.js to fit what I need. But how can I remove event listener of a object's function without removing all other listener?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tom10271
  • 4,222
  • 5
  • 33
  • 62

2 Answers2

11

It's not being removed because it's a different object.

.bind() returns a new object every time.

You need to store it somewhere and use it to remove:

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

then

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

or

this.notification.removeEventListener(barcodeScanner.NEW_READING, handler);
zerkms
  • 249,484
  • 69
  • 436
  • 539
1

Here is the way how to bind and unbind event handler in some component:

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);
Nazar Vynnytskyi
  • 4,647
  • 2
  • 21
  • 22