A text node stores textual character data without a tag name, attributes, or child nodes. In a virtual DOM, it is represented by a type and a value. section 3.6 section 3.2
Handle a text node through three small responsibilities:
- Identify it with DOM_TYPES.TEXT, whose value is 'text', so rendering code can distinguish it from element and fragment nodes. section 3.4
- Create it with a virtual node such as { type: DOM_TYPES.TEXT, value: str }. section 3.6
- Mount it with document.createTextNode(value), save the real DOM node in vdom.el, and append it to the parent. section 4.1.2
- Patch only changed text by comparing old and new values and assigning the new value to the DOM node's nodeValue property. section 8.2.4
Create and mount text
const vdom = hString('I need more coffee') mountDOM(vdom, document.body) The virtual node becomes a browser Text node, while vdom.el keeps the reference needed for later updates. section 3.6 section 4.1.2
Listing 8.9 Patching a text node (patch-dom.js)
function patchText(oldVdom, newVdom) {
const el = oldVdom.el
const { value: oldText } = oldVdom
const { value: newText } = newVdom
if (oldText !== newText) {
el.nodeValue = newText
}
}
Inspect the minimal patchText implementation: retain the existing DOM reference, compare values, and update nodeValue only when the text changes. section 8.2.4
