An event is a notification that something happened: a button was clicked, a key was pressed, or a network request completed. It may carry additional information, but it does not ask the application to act. A command does: add-todo, for example, requests a change to application state. Event names commonly describe what happened; command names describe what to do. section 5.1.1
To respond to a browser event:
- Listen for the relevant event, such as click on the Add button or keydown on the input. section 2.2.3
- Check any information needed to interpret it. A keydown matters for adding a TODO only when the key is Enter and the input is long enough. section 2.2.3
- Translate the event into an application action. Both clicking Add and pressing Enter can mean add-todo; the browser events themselves do not have that domain meaning. section 5.1.1
Two events, one TODO action
The same addTodo() function can handle both paths: addTodoInput.addEventListener('keydown', ({ key }) => { if (key === 'Enter' && addTodoInput.value.length >= 3) { addTodo() } }) addTodoButton.addEventListener('click', () => { addTodo() }) The handlers interpret different browser notifications as the same application action. section 2.2.3 section 5.1.1
Table 5.1 Mapping between browser events and application commands in the TODOs application
|
Browser event
|
Command
|
Explanation
|
|---|---|---|
|
Click the Add button.
|
add-todo
|
Clicking the Add button adds a new to-do item to the list.
|
|
Press the Enter key (while the input field is focused).
|
add-todo
|
Pressing the Enter key adds a new to-do item to the list.
|
|
Click the Done button.
|
remove-todo
|
Clicking the Done button marks the to-do item as done, removing it from the list.
|
|
Double-click a to-do item.
|
start-editing-todo
|
Double-clicking a to-do item sets the to-do item in edit mode.
|
Compare how several browser actions map to TODO commands. Notice that different events can produce the same command, while a double-click has a different meaning. section 5.1.1
Components also use events, but a child component’s custom event is not a DOM event. It has a name and can contain a payload. While props carry data from parent to child, an emitted event lets a child communicate with a parent that listens for it. The parent defines a handler; the child stores the registered handler so it can be called when the event is emitted. section 11.2 section 11.0
A small component implementation can keep registered handlers in an event-handler registry, subscribe them through a dispatcher when the component mounts, and unsubscribe when it unmounts. This event-based interface resembles passing a callback from parent to child: React’s JSX example passes an onClick handler explicitly, whereas Vue’s template example emits and listens for a custom event. section 11.3 section 11.2 section 11.0

















