Home
← All questions

EventEmitter class with subscribe, emit, and unsubscribe in JavaScript

EasyPremiumJavaScript

Asked at BookMyShow · DP World

JavaScript interview practice: Implement an EventEmitter that supports per-subscription removal.

Problem

UI components, websocket clients and analytics layers all rely on events, and building an EventEmitter class in JavaScript with subscribe, emit and unsubscribe is a frequent frontend interview task.

Implement a class EventEmitter with two methods:

  • subscribe(eventName, callback) registers callback for eventName and returns a subscription handle object with a remove() method.
  • emit(eventName, ...args) calls every callback currently subscribed to eventName, passing along all args.

Requirements

  • Multiple callbacks can subscribe to the same event; emit calls each of them, in the order they subscribed.
  • All extra arguments passed to emit are forwarded to each callback unchanged.
  • Calling remove() on a handle stops only that subscription; other subscribers to the same event keep receiving events.
  • Emitting an event that has no subscribers (or whose subscribers were all removed) does nothing and does not throw.
  • Separate EventEmitter instances do not share subscriptions.

Example

const emitter = new EventEmitter();

const a = emitter.subscribe("save", (id, ok) => console.log("A", id, ok));
const b = emitter.subscribe("save", (id) => console.log("B", id));

emitter.emit("save", 7, true);
// A 7 true
// B 7

a.remove();
emitter.emit("save", 8, false);
// B 8

emitter.emit("unknown", 1); // (nothing logged)

Follow-ups

  • What should happen if the same callback is subscribed twice?
  • What if a callback removes itself or another subscription while emit is running?
  • How would you add a once(eventName, callback) method?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium