destroyDOM removes the real DOM associated with a mounted virtual node and clears the virtual node’s DOM references. It reverses mountDOM so a rendered view can be removed cleanly. section 4.1.7 section 4.2
Handle each virtual-node type with a focused responsibility:
- Text nodes remove their text node from its parent. section 4.2
- Element nodes remove themselves, recursively destroy their children, detach event listeners, and delete listeners. section 4.2.2
- Fragment nodes recursively destroy their children without removing the fragment’s referenced parent element. section 4.2.3
- Every successfully destroyed node loses its el property, marking it as no longer mounted and allowing its DOM element to be collected. section 4.2
- Component nodes delegate cleanup to the component’s unmount method, which can recursively destroy its virtual DOM tree. section 11.1.3
Removing a mounted view
After mountDOM(vdom, document.body) renders a section containing a headline and paragraph, destroyDOM(vdom) removes that section and leaves the body empty. For a fragment mounted inside an existing body, it removes only the fragment’s children, not the body. section 4.1.7 section 4.2.3
Listing 4.4 Destroying the virtual DOM (destroy-dom.js)
import { removeEventListeners } from './events'
import { DOM_TYPES } from './h'
export function destroyDOM(vdom) {
const { type } = vdom
switch (type) {
case DOM_TYPES.TEXT: {
removeTextNode(vdom)
break
}
case DOM_TYPES.ELEMENT: {
removeElementNode(vdom)
break
}
case DOM_TYPES.FRAGMENT: {
removeFragmentNodes(vdom)
break
}
default: {
throw new Error(`Can't destroy DOM of type: ${type}`)
}
}
delete vdom.el
}
// TODO: implement removeTextNode()
// TODO: implement removeElementNode()
// TODO: implement removeFragmentNodes()
The central switch-based implementation shows how destroyDOM dispatches cleanup by virtual-node type before deleting el. section 4.2
function removeFragmentNodes(vdom) {
const { children } = vdom
children.forEach(destroyDOM)
}
The fragment helper demonstrates the essential recursive operation: destroy every child while leaving the fragment’s container untouched. section 4.2.3
