liveBook · Manning

addEventListeners

As explained in Build a Frontend Web Framework (From Scratch)

A book-specific helper function that registers multiple event handlers described by an object on a DOM element.

addEventListeners registers the event handlers stored in a virtual node’s on object. It accepts an optional listener map and DOM element, adds each handler, and returns the registered listeners. section 4.1.5 section 4.1.4

Its implementation separates three small responsibilities:

  • Iterate over event names and handler functions with Object.entries(). section 4.1.5
  • Delegate each individual registration to addEventListener(eventName, handler, el). section 4.1.5
  • Store the returned handlers in a new object for the virtual node’s listeners property. section 4.1.5 section 10.3

Registering a button’s handlers

A virtual button can describe several handlers together: on: { mouseover: () => console.log('almost yay!'), click: () => console.log('yay!'), dblclick: () => console.log('double yay!') }. Passing this object and the button element to addEventListeners attaches all three handlers. section 4.1.5

export function addEventListeners(listeners = {}, el) {
  const addedListeners = {}

  Object.entries(listeners).forEach(([eventName, handler]) => {
    const listener = addEventListener(eventName, handler, el)
    addedListeners[eventName] = listener
  })

  return addedListeners
}

The complete helper shows the default empty listener map, per-entry delegation, and separate returned mapping. section 4.1.5

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Implements object iteration and delegation, then defers stateful handler wrapping to later component behavior.
Examples
Uses a button virtual node with mouseover, click, and dblclick handlers.
What it assumes
Assumes JavaScript objects and DOM elements while teaching listener-map registration through small helper functions.
What you can do after
Build it from scratch by iterating over a listener object and attaching each handler to a DOM element.
How it connects
Connects virtual DOM nodes, DOM elements, event listeners, component state, and mountDOM.

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.