Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove ALL event listeners in NodeJS EventEmitter?

Tags:

node.js

events

How to remove ALL event listeners in NodeJS?

like image 965
Maxmaxmaximus Avatar asked Aug 07 '17 05:08

Maxmaxmaximus


People also ask

How do I delete all event listeners at once?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Should you always remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.

Why should you remove event listeners once they are no longer used?

Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.

Should I remove event listeners before removing elements?

Removing the event listener first always results in lower memory usage (no leaks).


1 Answers

Perhaps the simplest way would be to just replace the eventEmitter object with a new one that would have no listeners registered on it.

If you really need to clear all registered events because other code has a reference to the current emitter object, then you can do it using the public API like this:

emitter.removeAllListeners();

Which is described in the node.js doc here. That function can pass an event name to remove all listeners just for that event or, if no event name is passed, it removes all listeners for all events.

FYI, you can also get all event names that have any registered event handlers with the emitter.eventNames() method and then you can remove all listeners for any given event name with emitter.removeAllListeners(eventName). So, you could also iterate through all the event names and remove all listeners for any of them you wanted to.

like image 115
jfriend00 Avatar answered Oct 23 '22 10:10

jfriend00