Node-style EventEmitter
Medium · Events
Implement a subset of Node's EventEmitter that behaves exactly like the real one:
- on(event, fn) adds a listener at the end. Adding the same function twice means it runs twice.
- prependListener(event, fn) adds a listener at the START.
- once(event, fn) adds a listener that is removed right BEFORE it is called the first time.
- off(event, fn) removes ONE registration of fn: the most recently added one. It also removes a once registration of fn. Unknown listeners are ignored.
- emit(event, payload) calls the listeners in order and returns true if the event had listeners, otherwise false.
- listenerCount(event) returns how many listeners are registered.
(on, once, off and prependListener return this in Node. We skip the special behaviour of the "error" event.)
The driver runEmitter(ops) is already written. Listeners are identified by ids and each one logs "<id>:<payload>". emit and count ops also log their results.