Course contentsShow
← JavaScript
Lesson 2416 of 2,72349. Common Patterns and IdiomsFree lesson

Registering Event Listeners with on()

How to register multiple listeners for the same event and understand listener execution order.

Registering Event Listeners with on()

You'll learn how to attach multiple listeners to the same event and understand the order in which they execute.

The Core Idea

Once you have an Event Emitter instance, you need a way to register functions that respond to events. The on() method (sometimes called addListener()) lets you attach callback functions to specific event names. When that event is emitted later, all registered callbacks execute in the order they were registered.

Think of it like subscribing to a newsletter: multiple people can sign up for the same newsletter, and when it's sent out, everyone receives it in the order they subscribed.

Registering Multiple Listeners

const emitter = new EventEmitter();

// First listener
emitter.on('data', (value) => {
  console.log('First listener:', value);
});

// Second listener for the same event
emitter.on('data', (value) => {
  console.log('Second listener:', value);
});

// Third listener
emitter.on('data', (value) => {
  console.log('Third listener:', value);
});

// Emit the event
emitter.emit('data', 42);

// Output:
// First listener: 42
// Second listener: 42
// Third listener: 42

Execution Order Guarantee

Listeners execute synchronously in the exact order they were registered. This predictability is crucial when one listener's side effects matter to the next. The event emitter maintains an internal array of callbacks per event name and iterates through them sequentially.

emitter.on('save', () => console.log('Validate data'));
emitter.on('save', () => console.log('Write to database'));
emitter.on('save', () => console.log('Log success'));

emitter.emit('save');
// Always: Validate → Write → Log

Key Takeaway: Use on() to register multiple listeners for the same event; they execute synchronously in registration order, ensuring predictable behavior.