Blog>
Snippets

Implementing Event Emitter

Create a custom event emitter to understand how asynchronous events are handled in Node.js.
class EventEmitter {
  constructor() {
    this.events = {};
  }

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

  emit(event, ...args) {
    const listeners = this.events[event];
    if (listeners) {
      listeners.forEach(listener => {
        listener(...args);
      });
    }
  }

  off(event, listener) {
    const listeners = this.events[event];
    if (listeners) {
      this.events[event] = listeners.filter(l => l !== listener);
    }
  }
}
This is a simple EventEmitter class implementation. It has three main methods: on(event, listener) to register event listeners, emit(event, ...args) to trigger events, and off(event, listener) to remove specific event listeners.