SomePerson
SomePerson

Reputation: 1309

How to remove a specific event listener?

I have these two event listeners:

client.on("foo" () => {console.log("bar")});
client.on("foo" () => {console.log("foobar")});

I can set them as variables:

var foobar = client.on("foo" () => {console.log("bar")});
var foofoobar = client.on("foo" () => {console.log("foobar")});

The .on function returns the eventEmitter, or in this case: client.

Can I remove the foofoobar listener, but keep the foobar listener? removeListener() sounds like something that should work, but it does not. It will removes all events named foo.

I could do something hackish like this:

client.on("foo" () => {console.log("bar")});
client.on("foo" () => {console.log("foobar")});
client.removeListener("foo");
client.on("foo" () => {console.log("bar")});

However, that is not DRY*. That is WET*, and what I consider as bad practice.

I'm writing this in Typescript, but I assume that wouldn't matter in this case, as this is about Node.JS rather than the TS Engine...

Upvotes: 1

Views: 742

Answers (2)

ray
ray

Reputation: 27245

If you declare the function separately instead of inline, you can remove it the same way you add it:

const handler = () => console.log("bar");

client.on(“foo”, handler);
client.off(“foo”, handler);

Upvotes: 1

Nick
Nick

Reputation: 16576

You can remove the listener by providing it as the second argument to removeListener. Importantly, you need a reference to the same function to do so.

const foobarFunction = () => {console.log("foobar")};

client.on("foo" () => {console.log("bar")});
client.on("foo", foobarFunction);
client.removeListener("foo", foobarFunction);

Upvotes: 0

Related Questions