Node.js
removeListener
Learn to remove listeners with .removeListener.
removeListener
The removeListener method removes a previously added listener. Signature: emitter.removeListener(eventName, listener). The alias off does the same job.
Key point: you must pass the same function reference. Anonymous functions create a new reference each time, so they cannot be removed. That is why you first store the listener in a variable: const handler = () => console.log("beep");. Then remove it with emitter.removeListener("sound", handler). Cleaning up unneeded listeners is a good habit to prevent memory leaks.
Listener reference
If an anonymous listener is written directly inside on, its reference is lost: emitter.on("sound", () => {}). You cannot remove this listener afterwards. Solution: define the function first, then pass the same variable to both on and removeListener.
Example: const handler = () => console.log("beep"); emitter.on("sound", handler); emitter.emit("sound"); emitter.removeListener("sound", handler); emitter.emit("sound");. The first emit prints beep; the second emit prints nothing because the listener was removed. This control is the core way to manage event flow.
Exercise Add, call, then remove a listener
Define a function named handler that prints "Beep!". Add it with emitter.on("beep", handler). Call emit("beep"). Then remove it with removeListener("beep", handler) and call emit("beep") again. The output should be only one Beep!.
Show example solution
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
const handler = () => console.log("Beep!");
emitter.on("beep", handler);
emitter.emit("beep");
emitter.removeListener("beep", handler);
emitter.emit("beep");
Test yourself
-
Match each method to its role
- removeListener
- Removes a listener
- off
- Alias of removeListener
- on
- Adds a listener
- emit
- Fires the event
-
What does removeListener require?
emitter.removeListener(name, fn)
- Only the event name
- The number of times the event was emitted
- The event name and the listener count
- The same function reference
Show answer
The same function reference — The same function reference must be passed.
-
Complete the removal line
emitter.removeListener("ses", ____);
Show answer
emitter.removeListener("ses", handler);
Next lesson: error event