liveBook · Manning

patchEvents

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

patchEvents is a book-specific function that synchronizes DOM event listeners with virtual-node event handlers and returns the attached listeners.

patchEvents keeps a DOM element’s event listeners aligned with the old and new virtual-node handlers. It removes obsolete listeners, replaces changed ones, adds new ones, and returns the listeners now attached. section 8.2.5

Its implementation follows a small sequence:

  • Compare oldEvents and newEvents with objectsDiff() to identify removed, added, and updated event names. section 8.2.5
  • Remove listeners for removed or updated events by using the corresponding functions stored in oldListeners. section 8.2.5
  • Attach listeners for added or updated handlers and collect the attached listener functions in a new object. section 8.2.5
  • Save the returned object as newVdom.listeners so a later patch can remove these listeners. section 8.2.5

Patching a changed click handler

When a virtual node changes its click handler, patchEvents removes the old stored listener, attaches the new handler, and returns the replacement listener for future updates. section 8.2.5

Listing 8.11 Patching an element node (patch-dom.js)
function patchElement(oldVdom, newVdom) {
  const el = oldVdom.el
  const {
    class: oldClass,
    style: oldStyle,
    on: oldEvents,
    ...oldAttrs
  } = oldVdom.props
  const {
    class: newClass,
    style: newStyle,
    on: newEvents,
    ...newAttrs
  } = newVdom.props
  const { listeners: oldListeners } = oldVdom

  patchAttrs(el, oldAttrs, newAttrs)
  patchClasses(el, oldClass, newClass)
  patchStyles(el, oldStyle, newStyle)
  newVdom.listeners = patchEvents(el, oldListeners, oldEvents, newEvents)
}

// TODO: implement patchAttrs()

// TODO: implement patchClasses()

// TODO: implement patchStyles()

// TODO: implement patchEvents()

The element-patching listing shows where patchEvents receives old listeners and event maps, then stores its result on the new virtual node. section 8.2.5

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

How deep it goes
Defines the diff, removal, attachment, and listener-storage steps without detailing handler-wrapper internals.
Examples
Uses old and new event maps, stored listeners, and changed event-handler cases.
What it assumes
Assumes virtual nodes, props, DOM elements, event handlers, and object-diff utilities.
What you can do after
Build it from scratch by diffing handlers, removing stale listeners, attaching replacements, and preserving listener references.
How it connects
Connects virtual DOM, event handlers, DOM event listeners, patchElement, and reconciliation.

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.