Chapter 4. Core APIs
There are a lot of APIs in Node, but some of them are more important than others. These core APIs will form the backbone of any Node app, and you’ll find yourself using them again and again.
Events
The first API we are going to look at is
the Events API. This is
because, while abstract, it is a fundamental piece of making every other
API work. By having a good grip on this API, you’ll be able to use all the
other APIs effectively.
If you’ve ever programmed JavaScript in the browser, you’ll have used events before. However, the event model used in the browser comes from the DOM rather than JavaScript itself, and a lot of the concepts in the DOM don’t necessarily make sense out of that context. Let’s look at the DOM model of events and compare it to the implementation in Node.
The DOM has a user-driven event model based on user interaction, with a set of interface elements arranged in a tree structure (HTML, XML, etc.). This means that when a user interacts with a particular part of the interface, there is an event and a context, which is the HTML/XML element on which the click or other activity took place. That context has a parent and potentially children. Because the context is within a tree, the model includes the concepts of bubbling and capturing, which allow elements either up or down the tree to receive the event that was called.
For example, in an HTML list, a click event on
an <li> can be captured by a
listener on the <ul> that is its parent. Conversely, ...