Search code examples
javascripteventemitter

Node.js EventEmitter2; How to remove listeners added with onAny


How can I remove all event listeners that listen on any event?

I've tried removeAllListeners() but it's not working. Am I missing something?

const ee = new EventEmitter2()
  
ee.onAny(() => console.log('hello was fired'))
setInterval(() => ee.emit('hello'), 500)

setTimeout(() => {
  ee.removeAllListeners()
  console.log('removed all listeners')
}, 1500)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/eventemitter2.min.js"></script>


Solution

  • It seems as though the API for this library is somewhat confusing. To deregister onAny() listeners, you use offAny().

    Drilling down into the source reveals that removeAllListeners() doesn't really touch the _all array that tracks the listeners for any event. It just runs init() and configure() on the listener again none of which touches that _all array.

    Also note your issue on the GitHub page here: removeAllListeners does not remove listeners added with onAny #235

    If you want to actually remove them all do something like this:

    const ee = new EventEmitter2();
    
    ee.onAny(() => console.log("any event was fired"));
    ee.on("hello", () => console.log("hello event was fired"));
    
    setInterval(() => ee.emit("hello"), 500);
    
    setTimeout(() => {
      console.log("Removing any listener");
      ee.offAny();
    }, 1500);
    
    setTimeout(() => {
      console.log("Removing all listeners");
      ee.removeAllListeners();
    }, 3000);
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/eventemitter2.min.js"></script>