Build an event emitter
Several parts of an app care about the same button. If each one reaches for the button and wires its own handler, the button has to know about all of them, and adding a listener means editing the button's code. You want the opposite: parts subscribe to what they care about, and the button announces it once.
An event emitter is that publish–subscribe pattern. Objects register interest
in a named event with on, and later something fires that event with emit.
Every registered listener runs. off removes a listener so it stops receiving
events.
The shape keeps a map from event name to a list of handlers:
class EventEmitter {
constructor() {
this.handlers = new Map();
}
on(event, handler) {
const list = this.handlers.get(event) || [];
this.handlers.set(event, [...list, handler]);
}
off(event, handler) {
const list = this.handlers.get(event) || [];
this.handlers.set(
event,
list.filter((fn) => fn !== handler),
);
}
emit(event, ...args) {
for (const handler of this.handlers.get(event) || []) {
handler(...args);
}
}
}
on appends to the event's list; emit looks the list up and calls each handler
with the arguments; off filters the handler back out. An event with no
listeners does nothing.
Export EventEmitter from index.js. Your job is to make on, emit, and
off work together.
Challenge
Several parts of an app care about the same event, but you do not want each one
wired directly to the source. Export an EventEmitter class from index.js so
they can subscribe and be notified.
The class has three methods: on(event, handler) registers a listener,
off(event, handler) removes it, and emit(event, ...args) calls every
registered listener with the given arguments. Listeners run in the order they
were added, and a listener removed with off must not receive later events.