EventEmitter Polyfill

Design PatternsPolyfill

Implement an EventEmitter class with four methods.

on(eventName, listener) — register a listener, return this

off(eventName, listenerToRemove) — remove a specific listener, return this

emit(eventName, ...args) — call all listeners for the event, return true if any existed

once(eventName, listener) — register a listener that auto-removes itself after one call, return this

Examples

Example 1
Input
const e = new EventEmitter();
e.on('msg', m => console.log(m));
e.emit('msg', 'hello');
e.emit('msg', 'world');
Output
hello
world
Explanation
on() registers a persistent listener.
Example 2
Input
const e = new EventEmitter();
e.once('login', user => console.log('logged in:', user));
e.emit('login', 'Alice');
e.emit('login', 'Bob');
Output
logged in: Alice
Explanation
once() fires only for the first emit, then auto-removes.

Constraints

  • In emit(), iterate over a copy of the listener array (`.slice()`) so a listener that calls off() on itself does not break the loop

Notes

  • once() stores a `wrapper` function in the listeners array — off() must remove `wrapper`, not the original listener

Hints

Read the full write-up for EventEmitter Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it