FrontendPro

32Implement an EventEmitter with on, off, emit, and once

mediumAbout 35 minutesCodingeventsclassespub-sub

Problem

Implement an EventEmitter class, similar to Node's:

  • on(event, listener): add a listener. Returns the emitter, so calls can be chained.
  • once(event, listener): add a listener that removes itself after its first call.
  • off(event, listener): remove a listener. Works for listeners added with once too.
  • emit(event, ...args): call every listener for event in the order they were added, with this set to the emitter. Return true if there were listeners, otherwise false.
  • listenerCount(event): the number of listeners for event.
const chat = new EventEmitter();
const onMessage = (from, text) => console.log(`${from}: ${text}`);
chat.on("message", onMessage);
chat.once("message", () => console.log("first message!"));
chat.emit("message", "Asha", "Hi"); // both listeners run
chat.emit("message", "Ravi", "Hello"); // only onMessage runs
chat.off("message", onMessage);

Requirements

  • The same listener added twice is called twice, and off removes one of them (the most recently added).
  • A listener that removes itself, or another listener, during emit must not cause others to be skipped.
  • A listener added during emit is not called in that same emit.
  • on throws a TypeError when the listener is not a function.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

Event Emitter - Leetcode 2694 - JavaScript 30-Day ChallengeNeetCodeIO on YouTubeOpen on YouTube
Event Emitter in JS - HARD JS Interview Questions | Part 3Piyush Garg on YouTubeOpen on YouTube

Step-by-step

Use a Map from event name to an array of listeners. A Map accepts any event name, including "constructor" or a Symbol, without clashing with object properties.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever