Event-Driven Programming
Event-driven programming is a paradigm where the flow of the program is determined by events: user actions like clicks and keystrokes, system notifications, or messages from other programs. Instead of running code sequentially from start to finish, an event-driven program waits for events and responds to them.
In the DOM chapter, you learned to attach event listeners to respond to clicks and other user actions. This chapter takes event-driven programming as a paradigm. We look at how events flow through the DOM, how to create custom events, and how Node.js uses the same pattern for I/O operations.
Here is a simple button click:
const button = document.querySelector("#myButton");
button.addEventListener("click", () => {
console.log("Button was clicked!");
});
console.log("Waiting for clicks...");
The program does not stop at the addEventListener line. It registers the function (called an event handler or listener) and continues. When the user clicks the button, JavaScript calls the handler function.
Interactive applications need this model. A web page has to respond to user input without freezing while it waits. You cannot write:
// This doesn't work!
const click = waitForClick(); // Would freeze the page
doSomething(click);
Instead, you describe what should happen when an event occurs:
// This works!
button.addEventListener("click", (event) => {
doSomething(event);
});
JavaScript relies on event-driven programming in both places it runs. In the browser, it handles user interactions and DOM changes. In Node.js, it handles I/O operations like file reads and network requests.
Learning Outcomes
- Explain event-driven programming as a paradigm and why JavaScript relies on it in both the browser and Node.js
- Register, remove, and work with browser event listeners and the event object
- Control event flow through the DOM using propagation, delegation, and stopPropagation
- Create and dispatch custom events to enable communication between parts of an application
- Apply the EventEmitter pattern for event-driven programming in Node.js