Overview
Build the publish/subscribe object behind Node's EventEmitter and DOM listeners: register callbacks by name, remove them, fire them with data.
- A Map from event names to arrays of functions
- Calling listeners with ...args
- Removing a listener by reference
Short Course
An emitter keeps a list of functions per event name. Trap: off needs the
same function you passed to on, so an inline arrow function can never
be removed — keep it in a variable.
const listeners = new Map();
const onSave = (file) => console.log("saved", file);
listeners.set("save", [onSave]);
listeners.get("save").forEach((fn) => fn("a.txt")); // saved a.txt
listeners.get("save").filter((fn) => fn !== onSave); // []
Task
Write class Emitter with on(event, fn), off(event, fn) and
emit(event, ...args), which calls every listener of event in order with
the arguments, e.g. emit("add", 2, 3) calls each "add" listener with 2, 3.
Test Suites
Pending
Next
Output