mountDOM converts a virtual DOM tree into real browser DOM nodes and inserts them under a chosen parent element, hiding direct Document API work from application developers. section 4.1
Implement mounting as a small dispatcher with three responsibilities:
- Dispatch text, element, and fragment virtual nodes to their corresponding creation functions. section 4.1.1
- Store each created real node in the virtual node’s el property for later updates and removal. section 4.1
- Store event-listener references in listeners so handlers can later be removed. section 4.1
- Throw an error when a virtual node has an unsupported type, making malformed input easier to diagnose. section 4.1.1
- Accept an insertion index when nodes must appear within existing children rather than only at the end. section 8.1
Mounting a login form
Define a virtual form containing username and password inputs plus a Login button, then call mountDOM(vdom, document.body). The resulting body contains the corresponding form, while virtual nodes retain element and listener references. section 4.1 section 4.1.7
Listing 4.1 The mountDOM() function mounting the virtual DOM (mount-dom.js)
import { DOM_TYPES } from './h'
export function mountDOM(vdom, parentEl) {
switch (vdom.type) {
case DOM_TYPES.TEXT: {
createTextNode(vdom, parentEl) #1
break
}
case DOM_TYPES.ELEMENT: {
createElementNode(vdom, parentEl) #2
break
}
case DOM_TYPES.FRAGMENT: {
createFragmentNodes(vdom, parentEl) #3
break
}
default: {
throw new Error(`Can't mount DOM of type: ${vdom.type}`)
}
}
}
// TODO: implement createTextNode()
// TODO: implement createElementNode()
// TODO: implement createFragmentNodes()
Use the dispatcher listing to trace how virtual node types select text, element, or fragment mounting and how unsupported types fail. section 4.1.1
