CodePark/ problems / Event emitter
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Event emitters and observable state

Event emitter

mediumabout 25 minutes in an interview

Implement an EventEmitter class. Code registers listeners (callback functions) for named events, and emit calls them.

  • on(event, listener) registers listener for event. Registering the same function twice means it runs twice.
  • once(event, listener) registers a listener that is removed just before its first call.
  • off(event, listener) removes one registration of listener for event: the earliest one, whether it came from on or once. Removing something that isn't registered does nothing.
  • emit(event, ...args) calls every listener for event with args, in the order they were registered. It returns true if the event had at least one listener and false otherwise.
  • listenerCount(event) returns how many registrations event has.
  • on, once and off return the emitter, so calls can be chained.

Changes during an emit: an emit calls exactly the listeners registered when it started. A listener removed by an earlier listener in the same emit still runs this time. A listener added during the emit first runs on the next emit. A once listener is removed before it runs, so if it emits the same event again, it doesn't run a second time.

Input: const e = new EventEmitter(); e.on('save', log); e.emit('save', 'doc-1') Output: true; log was called with 'doc-1'
Input: e.once('ready', fn); e.emit('ready'); e.emit('ready'); Output: fn is called once
Input: e.emit('nobody-listens') Output: false