Your own EventEmitter
Write a simplified version of Node.js `EventEmitter` – on, once, off, emit and the special `error` event. The Observer pattern in practice, with the traps of modifying the list during emission.
EventEmitter is the heart of Node.js – streams, HTTP servers and sockets all emit events. Interviews often ask: "write your own". The task checks the Observer pattern and a few subtleties that are easy to trip over.
Task
An EventEmitter class with these methods (Python: listener_count instead of listenerCount, *args arguments):
| Method | Behaviour |
|---|---|
on(event, listener) | registers a listener; returns an unsubscribe() function (calling it again is safe) |
once(event, listener) | like on, but the listener is removed before its first call; also returns unsubscribe() |
off(event, listener) | removes one registration of this listener (the most recently added); works for once listeners too; returns true when something was removed |
emit(event, ...args) | synchronously calls the listeners in registration order with args; returns true when any listener was registered |
listenerCount(event) | number of listeners registered for the event |
Rules:
- the same listener registered twice is called twice,
- the list of listeners is frozen when
emitstarts: listeners added during emission are called from the next emit on, and removing one during emission does not stop the current round, - an exception thrown by a listener stops the emission and propagates out of
emit(as in Node.js), emit('error', err)with noerrorlisteners throwserr(if it is anError/ exception), otherwise anError/RuntimeErrorwith the messageUnhandled error.
Example
| Code | Effect |
|---|---|
const off = e.on('msg', log); e.emit('msg', 'hi', 1) | log('hi', 1), returns true |
e.once('ready', init); e.emit('ready'); e.emit('ready') | init called once |
off(); e.emit('msg') | nothing happens, returns false |
e.emit('error', new Error('boom')) | throws Error('boom') |
Constraints
- Up to 100,000 registrations and emissions per test; event names are strings.
Expected complexity
on, once, listenerCount – O(1); emit – O(k) for k listeners; off – O(k).
Topics: Observer
Related articles
- Observer: notify everyone without knowing anyone
The Observer pattern through a pierogi place's pantry: when the cheese runs out, the menu, the shopping list and alerts react on their own, and the pantry does not know they exist. Subscribing, unsubscribing, pitfalls and code in five…