liveBook · Manning

Element destruction

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

Destroying is the process of removing the browser DOM nodes created from a virtual DOM tree and detaching their event listeners.

Element destruction removes the DOM nodes created from a virtual DOM element and detaches their event listeners. The mechanism has three responsibilities: remove the element, recursively destroy its children, and clean up listeners and virtual-node references. section 4.2.2 section 4.3

Destroy an element in this order:

  • Call the DOM element’s remove() method. section 4.2.2
  • Call destroyDOM() for every child so nested text, elements, fragments, and components are destroyed recursively. section 4.2.2 section 11.1.3
  • Use removeEventListener() with each stored event name and handler, then delete the listeners and el properties from the virtual node. section 4.2.2 section 11.1.3

Why full destruction can disrupt input

When application state changes, destroying and recreating the entire DOM replaces the focused input element. A TODO input therefore loses focus after every keystroke; later DOM-diffing work addresses this limitation. section 6.3.3

function removeElementNode(vdom) {
  const { el, children, listeners } = vdom

  el.remove()
  children.forEach(destroyDOM)

  if (listeners) {
    removeEventListeners(listeners, el)
    delete vdom.listeners
  }
}

This implementation shows the complete element-destruction sequence: remove the node, recurse through children, and detach listeners before deleting stored listener data. section 4.2.2

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

How deep it goes
Implements removal, recursive cleanup, listener detachment, component unmounting, and virtual-node deletion; defers optimized DOM preservation.
Examples
Demonstrates cleanup with button listeners and illustrates focus loss in a state-driven TODO input.
What it assumes
Assumes virtual DOM nodes store DOM elements, children, and listeners, while teaching listener removal through EventTarget methods.
What you can do after
Build it from scratch by recursively removing nodes, detaching stored handlers, and unmounting component virtual nodes.
How it connects
Connects virtual DOM, DOM nodes, event listeners, fragments, components, and unmounting.

Related concepts

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.