Emitting Events with emit()
What you'll learn: How to trigger events synchronously and pass multiple arguments to all registered listeners in your custom Event Emitter.
The Core Mechanism
Now that you've registered listeners with on(), you need a way to trigger those events. The emit() method is your event broadcaster—it fires an event by name and immediately calls all registered listeners for that event, passing along any data you provide.
When you call emit('eventName', arg1, arg2, ...), the Event Emitter looks up all functions registered for 'eventName' and executes them synchronously, one after another, in the order they were registered. Each listener receives all the arguments you passed after the event name.
How It Works
Inside your Event Emitter class, emit() typically:
- Checks if the event name exists in the listeners map
- Retrieves the array of listener functions
- Loops through each function and calls it with the provided arguments
- Returns
trueif listeners were called,falseif none existed (common convention)
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
}
emit(event, ...args) {
if (!this.events[event]) {
return false;
}
this.events[event].forEach(listener => {
listener(...args);
});
return true;
}
}
const emitter = new EventEmitter();
emitter.on('data', (msg, count) => console.log(`${msg} (${count})`));
emitter.on('data', (msg) => console.log(`Also got: ${msg}`));
emitter.emit('data', 'Hello', 5);
// Logs: "Hello (5)"
// Then: "Also got: Hello"
Notice that execution happens immediately and in order—this is synchronous behavior, not deferred like setTimeout.
Key Takeaway: emit() triggers all registered listeners for an event synchronously, passing along any number of arguments to each listener in the order they were registered.