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).