All lessons

Event Listeners

8 min · TypeScript

Run code when something happens — the same pattern that powers clicks on the web.

TypeScript · Event Listeners0/5 cleared

Enemy 1 of 5

Every program you've written so far runs top to bottom the instant it starts. A large amount of real-world code — especially in the browser — is reactive instead: it registers a function ahead of time and waits, only running it later when something specific happens, like a click. This style is called event-driven programming.

On a web page, addEventListener('click', handler) tells the browser to run handler whenever the user clicks a particular element. You don't call handler yourself; you hand it to the browser in advance, and the browser decides when (or whether) to call it.

This runner doesn't have a web page to click on, but Node's EventEmitter mirrors the exact same idea in plain code: .on("click", handler) registers a function against a named event, and .emit("click") fires that event, running every handler registered for it. It's the same register-then-react shape you'll use constantly once you're building actual UIs.

You
Cargo Cultist

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Clicked!