If I do:
JavaScript
x
2
1
document.addEventListener("mousedown", this.foo);
2
and then inside function this.foo
then remove it with:
JavaScript
1
2
1
document.removeEventListener("mousedown", this.foo);
2
then it works.
However if I do:
JavaScript
1
2
1
document.addEventListener("mousedown", this.foo.bind(this));
2
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
JavaScript
1
6
1
var handler = this.foo.bind(this);
2
3
document.addEventListener("mousedown", handler);
4
5
document.removeEventListener("mousedown", handler);
6