removeListener
- Node.js course
- Intermediate
- Lesson 4/116
- 5 min
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.
Practice 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!.
Starter code
// Create an emitter instance
// write here
// Define the handler function
// write here
// Add a listener for "beep", fire once, remove, then fire again
// write hereSample 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");Expected output
Bip!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its role
| Term | Meaning |
|---|---|
removeListener |
Removes a listener |
off |
Alias of removeListener |
on |
Adds a listener |
emit |
Fires the event |
2 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 Correct answer
Explanation: The same function reference must be passed.
3 Complete the removal line
emitter.removeListener("ses", ____);
emitter.removeListener("ses", handler);
Explanation: The same handler reference is passed.