Skip to main content

Implement Event Emitter

Implementing an event emitter in JavaScript involves creating a class or object that can handle events. This typically includes methods for adding event listeners, emitting events, and removing event listeners. Here's a basic example to illustrate how you can implement an event emitter in JavaScript:

class EventEmitter {
constructor() {
this.events = {};
}

// Method to subscribe to an event
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
}

// Method to emit an event
emit(event, ...args) {
if (this.events[event]) {
this.events[event].forEach((listener) => {
listener(...args);
});
}
}

// Method to remove an event listener
off(event, listenerToRemove) {
if (this.events[event]) {
this.events[event] = this.events[event].filter((listener) => {
return listener !== listenerToRemove;
});
}
}
}

// Example usage
const emitter = new EventEmitter();

// Listener function
function logData(data) {
console.log(data);
}

// Subscribe to an event
emitter.on("data", logData);

// Emit the event
emitter.emit("data", "some data"); // Output: 'some data'

// Unsubscribe from the event
emitter.off("data", logData);

// Emitting the event again will have no effect as the listener has been removed
emitter.emit("data", "some data");

In this example, the EventEmitter class has three methods:

  • on(event, listener): Registers a listener for a given event.
  • emit(event, ...args): Triggers the event, calling all registered listeners with provided arguments.
  • off(event, listener): Removes a specific listener from an event.

This is a simplified version of what libraries like Node.js provide, but it demonstrates the core concept of an event emitter in JavaScript.