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

Implementing a Simple Event Emitter

Building a basic event emitter class with on/emit methods from scratch to understand the mechanics.

Implementing a Simple Event Emitter

You'll learn how to build a basic event emitter class from scratch, understanding how on() and emit() work under the hood.

Now that you understand the Event Emitter pattern conceptually, let's implement one ourselves. An event emitter is essentially an object that manages a registry of event names mapped to listener functions, then invokes those listeners when events are "emitted."

The Core Mechanism

Think of it like a bulletin board: listeners "subscribe" by pinning their contact info under specific topics (on()), and when someone posts news about a topic (emit()), everyone subscribed gets notified.

Basic Implementation

class EventEmitter {
  constructor() {
    this.events = {}; // Maps event names to arrays of listeners
  }

  on(eventName, listener) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(listener);
  }

  emit(eventName, ...args) {
    if (!this.events[eventName]) return;
    
    this.events[eventName].forEach(listener => {
      listener(...args);
    });
  }
}

// Usage
const emitter = new EventEmitter();

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

emitter.on('data', (value) => {
  console.log('Also got:', value);
});

emitter.emit('data', 42);
// Received: 42
// Also got: 42

The events object stores event names as keys and arrays of callback functions as values. When you call on(), you add a listener to the appropriate array. When you call emit(), you iterate through that array and invoke each listener with the provided arguments.

Key Takeaway: A simple event emitter is just an object that maintains a registry of event-to-listener mappings and provides methods to register listeners (on) and trigger them (emit), enabling decoupled communication between components.