Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove event listener of a object with .bind(this)? [duplicate]

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?

like image 604
tom10271 Avatar asked Dec 20 '22 06:12

tom10271


1 Answers

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);
like image 192
zerkms Avatar answered Dec 21 '22 19:12

zerkms