In JavaScript, what is the best way to remove a function added as an event listener using bind()?
Example
JavaScript
x
19
19
1
(function(){
2
3
// constructor
4
MyClass = function() {
5
this.myButton = document.getElementById("myButtonID");
6
this.myButton.addEventListener("click", this.clickListener.bind(this));
7
};
8
9
MyClass.prototype.clickListener = function(event) {
10
console.log(this); // must be MyClass
11
};
12
13
// public method
14
MyClass.prototype.disableButton = function() {
15
this.myButton.removeEventListener("click", ___________);
16
};
17
18
})();
19
The only way I can think of is to keep track of every listener added with bind.
Above example with this method:
JavaScript
1
20
20
1
(function(){
2
3
// constructor
4
MyClass = function() {
5
this.myButton = document.getElementById("myButtonID");
6
this.clickListenerBind = this.clickListener.bind(this);
7
this.myButton.addEventListener("click", this.clickListenerBind);
8
};
9
10
MyClass.prototype.clickListener = function(event) {
11
console.log(this); // must be MyClass
12
};
13
14
// public method
15
MyClass.prototype.disableButton = function() {
16
this.myButton.removeEventListener("click", this.clickListenerBind);
17
};
18
19
})();
20
Are there any better ways to do this?
Advertisement
Answer
Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:
A new function reference is created after
.bind()
is called.
See Does bind() change the function reference? | How to set permanently?
So, to add or remove it, assign the reference to a variable:
JavaScript
1
4
1
var x = this.myListener.bind(this);
2
Toolbox.addListener(window, 'scroll', x);
3
Toolbox.removeListener(window, 'scroll', x);
4
This works as expected for me.