Event emitters

Subscribe

An emitter keeps a list of listener functions and calls each one when something happens. The on function adds a listener, and the rest of the program stays unaware of who listens.

Type the listener once, for example as a function that takes a string message and returns void. Every subscriber then matches the same shape, and the compiler rejects mismatched handlers. The program subscribes one logger and calls it once, so the console shows the message.

type Listener = (msg: string) => void; const listeners: Array<Listener> = []; function on(listener: Listener): void { listeners.push(listener); } on(function show(msg: string): void { console.log(msg); }); for (const listener of listeners) { listener("hello"); }

hello

Publish

Publishing means looping over the list and calling every listener with the same event data. Emitters never return results from listeners, they only notify.

Keep emit synchronous for simple cases so the order of listeners matches the order of subscription. Async delivery can come later, once the basic flow is solid. The list and the subscribe helper are repeated here, so the block runs on its own, and emit prints one message.

type Listener = (msg: string) => void; const listeners: Array<Listener> = []; function on(listener: Listener): void { listeners.push(listener); } on(function show(msg: string): void { console.log(msg); }); function emit(msg: string): void { for (const next of listeners) { next(msg); } } emit("hello");

hello

Unsubscribe

Listeners that are never removed keep their closures alive for the life of the emitter. An off function finds the listener and splices it out of the array.

Always unsubscribe when a component is destroyed or a task finishes. Short lived subscribers on a long lived emitter are the classic source of slow memory growth. The program emits one message, removes the listener, emits again and prints how many listeners remain.

type Listener = (msg: string) => void; const listeners: Array<Listener> = []; function on(listener: Listener): void { listeners.push(listener); } function off(listener: Listener): void { const at: number = listeners.indexOf(listener); if (at !== -1) { listeners.splice(at, 1); } } function emit(msg: string): void { for (const next of listeners) { next(msg); } } const show: Listener = (msg: string): void => { console.log(msg); }; on(show); emit("first"); off(show); emit("second"); console.log(listeners.length);

first
0

Typed event maps

Real programs carry different payloads per event, so one string type is not enough. An event map type lists each event name next to its payload type, and a generic publish checks the pair.

The compiler then rejects a publish call with the wrong payload for the name. Renaming an event breaks at compile time instead of failing silently at runtime. The program publishes one start event and prints its name and its payload.

type Events = { start: string; stop: number; }; function publish<K extends keyof Events>(name: K, data: Events[K]): void { console.log(name); console.log(data); } publish("start", "ready");

start
ready

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an emitter keep?

    Answer

    A list of listener functions it calls on every event

    The list is the whole state of a simple emitter, and publishing walks it.

  2. Why type the listener once?

    Answer

    Every subscriber must match the same function shape

    One listener type means a handler with the wrong parameters is refused at compile time.

  3. Why keep emit synchronous at first?

    Answer

    The order of listeners then matches the order of subscription

    One loop over the list keeps the order obvious, and async delivery can be added once the flow is clear.

  4. What does off prevent?

    Answer

    A removed subscriber from being called again, and its closure from staying alive

    A listener left in the array keeps its closure, which is the classic slow memory growth.

  5. What does this program print? type Listener = (msg: string) => void; const listeners: Array<Listener> = []; function on(listener: Listener): void { listeners.push(listener); } on((msg) => { console.log("one: " + msg); }); on((msg) => { console.log("two: " + msg); }); for (const listener of listeners) { listener("hi"); }

    Answer

    one: hi / two: hi

    The listeners run in the order they were added to the list.

  6. What does this program print? type Listener = (msg: string) => void; const listeners: Array<Listener> = []; function on(listener: Listener): void { listeners.push(listener); } function off(listener: Listener): void { const at = listeners.indexOf(listener); if (at !== -1) { listeners.splice(at, 1); } } const show: Listener = (msg) => { console.log(msg); }; on(show); off(show); console.log(listeners.length);

    Answer

    0

    The one listener is removed again, so the list is empty.

  7. What does this program print? type Events = { start: string; stop: number; }; function publish<K extends keyof Events>(name: K, data: Events[K]): void { console.log(name, data); } publish("stop", 3);

    Answer

    stop 3

    The event map pairs stop with a number, so the call fits and prints both values.

  8. What does this program print? type Listener = (msg: string) => void; const listeners: Array<Listener> = []; const first: Listener = (msg) => { console.log("first " + msg); }; const second: Listener = (msg) => { console.log("second " + msg); }; listeners.push(first, second); for (const listener of listeners) { listener("go"); }

    Answer

    first go / second go

    Both listeners run once, in the order they sit in the array.

  9. What does the compiler say about this program? type Listener = (msg: string) => void; const listeners: Array<Listener> = []; listeners.push((count: number) => { console.log(count); });

    Answer

    error TS2345: Argument of type '(count: number) => void' is not assignable to parameter of type 'Listener'.

    The array only takes handlers of the declared shape, and a number parameter does not fit a string message.

  10. What does the compiler say about this program? type Events = { start: string; stop: number; }; function publish<K extends keyof Events>(name: K, data: Events[K]): void { console.log(name, data); } publish("stop", "ready");

    Answer

    error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

    The name picks the payload type from the map, and stop requires a number.

Article author: Arthur Isaev