Skip to content
Advertisement

How to removeEventListener on a callback with .bind(this) attached

If I do:

document.addEventListener("mousedown", this.foo);

and then inside function this.foo then remove it with:

document.removeEventListener("mousedown", this.foo);

then it works.

However if I do:

document.addEventListener("mousedown", this.foo.bind(this));

then the function is not removed.

Is there anything I can do? I must have the correct context inside foo.

Advertisement

Answer

this.foo.bind(this) is returning a function which is different than the function this.foo. So, what you need do is keep reference to the function returned by bind

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

document.addEventListener("mousedown", handler);

document.removeEventListener("mousedown", handler);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement