Reputation: 6294
I am using socket.io-client in a class, such that I do:
constructor() {
socket.on("a", this.a.bind(this));
socket.off("a", this.a.bind(this));
}
But when I construct (both on
and then off
fires), the socket still listens to "a".
The way I test this, is to console.log
on a
method, enter, and when "a" is received" console logs the event.
I also tried socket.removeListener
, but it did not work.
Perhaps it is because it is a class method? How can I fix this to work?
Upvotes: 0
Views: 145
Reputation: 707326
this.a.bind(this)
returns a unique function each time so when you then try to use .off()
with a second call to .bind()
, you get a different function and thus it won't match the original so .off()
doesn't find any matching function to remove.
You have to save the original bound function somewhere. You don't show enough of your code context to know where's a good place to save the original .bind()
result.
Conceptually, you want to do something like this:
// save this somewhere that is per-instance and that both methods can access
// perhaps as an instance variable from the constructor
this.boundA = this.a.bind(this);
ngOnInit() {
socket.on("a", this.boundA);
}
ngOnDestroy() {
socket.off("a", this.boundA);
}
Demo of the issue:
class Foo {
constructor() {
console.log(this.a.bind(this) === this.a.bind(this))
}
a() {
}
}
let f = new Foo();
Upvotes: 1