Event emitters

Contents
Subscribe
Publish
Unsubscribe
Typed event maps

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.

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); });

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.

// same list as above function emit(msg: string): void { for (const next of listeners) { next(msg); } } emit("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.

// same list as above function off(listener: Listener): void { const at: number = listeners.indexOf(listener); if (at !== -1) { listeners.splice(at, 1); } }

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.

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");

Next: Streams

Article author: Arthur Isaev

Related articles
TypeScript
TypeScript course: zero to hero in 100 lessons
What is TypeScript and where it runs
Install TypeScript
Your first program
tsconfig.json
Basic types
any, unknown, never
Arrays and tuples
Type aliases
Interfaces
Unions and literals
Function types
Parameters
Overloads
Generics
Constraints
Return types
Arrow functions
Callbacks
Narrowing
Assertions
Classes
Constructors
Modifiers
implements
Abstract classes
static
Getters and setters
Enums
ES modules
Decorators
Discriminated unions
Intersections
Mapped types
Conditional types
infer
Template literal types
keyof and typeof
Utility types
satisfies
const assertions
tsc CLI
tsconfig deep dive
Strict mode
Source maps
Declaration files
Linting
Formatting
Debugging
Project references
Publishing packages
Run with Node
npm scripts
argv and env
Files with fs
path and os
JSON IO
Dates
Crypto random
Timers
process
Callbacks to promises
Promises
async and await
Promise.all
Promise.race
HTTPS client
Abort and timeouts
Async error handling
Sequential vs parallel
Event loop
Tests with assert
Test layout
Fixtures
Test doubles
CI tests
DOM basics
DOM events
Fetch in browsers
Forms
Web storage
Npm packages
Bundling concept
SPA concepts
Typed API client
Hand-rolled validation
Iterators and generators
Mixins
Branding nominal types
Result types
Options objects
Builder
Event emitters
Streams
Workers
Deserialization
Capstone: todo CLI
Capstone: JSON API
Capstone: utils library
Modern TypeScript tour
Hero roadmap: the whole course on one page
Install TypeScript on Windows 11
Install TypeScript on Ubuntu
Install TypeScript on Rocky Linux
Install TypeScript on macOS
Install TypeScript on FreeBSD
TypeScript in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: