Methods
on(eventName, listener)
Registers a listener for a given event. Multiple listeners can be registered for the same event.
Parameters:
eventName(string) – Name of the event to listen to.listener(function) – Callback function to execute when the event is emitted.
Returns:
The EventEmitter instance (supports chaining).
Example:
1const emitter = new EventEmitter();3emitter.on("data", (msg) => {4 console.log("Received:", msg);5});7emitter.emit("data", "Hello World"); // Logs: Received: Hello World
Edge Cases:
- Multiple listeners can be attached to the same event; all will be called in order of registration.
- Chaining allows multiple
oncalls in sequence:emitter.on("a", fn1).on("b", fn2).
once(eventName, listener)
Registers a one-time listener that will be automatically removed after the first invocation.
Parameters:
eventName(string) – Event name.listener(function) – Callback function.
Returns:
The EventEmitter instance (supports chaining).
Example:
1emitter.once("connect", () => console.log("Connected!"));3emitter.emit("connect"); // Logs: Connected!4emitter.emit("connect"); // No output
Edge Cases:
- The listener is removed immediately after execution.
- Safe to attach multiple
oncelisteners to the same event.
emit(eventName, ...args)
Triggers an event, calling all registered listeners with the provided arguments.
Parameters:
eventName(string) – Event to trigger....args– Any number of arguments to pass to listeners.
Returns:
The EventEmitter instance (supports chaining).
Example:
1emitter.on("update", (oldVal, newVal) => {2 console.log(`Changed from ${oldVal} to ${newVal}`);3});5emitter.emit("update", 1, 2); // Logs: Changed from 1 to 2
Edge Cases:
- If no listeners exist for the event,
emitdoes nothing. - Errors in one listener do not prevent other listeners from executing; they are logged to console.
off(eventName, listener)
Removes a specific listener for an event. If no listener is provided, all listeners for that event are removed.
Parameters:
eventName(string) – Event name.listener(function, optional) – Specific listener to remove.
Returns:
The EventEmitter instance (supports chaining).
Example:
1const fn = (msg) => console.log(msg);2emitter.on("data", fn);3emitter.off("data", fn); // Removes fn
Edge Cases:
- Calling
offwith no listener removes all listeners for the event. - Safe to call
offon an event that has no listeners; does nothing.
removeAll(eventName)
Utility method to remove all listeners for a specific event.
Parameters:
eventName(string) – Event name.
Returns:
The EventEmitter instance (supports chaining).
Example:
1emitter.on("x", () => {});2emitter.removeAll("x"); // All listeners for "x" removed
listeners(eventName)
Returns an array of all registered listeners for an event.
Parameters:
eventName(string) – Event name.
Returns: Array of functions.
Example:
1emitter.on("msg", () => {});2console.log(emitter.listeners("msg").length); // 1
Edge Cases:
- Returns an empty array if no listeners are registered.