A mount method connects an application to a chosen DOM element and starts rendering. The application instance stores that parent element, creates the initial view, and begins the application lifecycle. section 5.2.1 section 5.2.2
A framework mount method typically coordinates these responsibilities:
- Accept the parent DOM element supplied by the developer. section 5.2.2
- Save the element so later rendering or unmounting can use it. section 5.2.2
- Create the root virtual DOM from the application view or root component. section 5.2.2 section 12.4
- Pass the virtual DOM to the DOM-mounting function. section 5.2.2
- Reject repeated mounting and provide a matching unmount operation when lifecycle guards are available. section 7.3 section 12.4
Mounting a root component
A small application instance can expose mount(_parentEl) { if (isMounted) throw new Error('The application is already mounted'); parentEl = _parentEl; vdom = h(RootComponent, props); mountDOM(vdom, parentEl); isMounted = true }. The caller supplies the DOM element once; later state updates use the saved virtual DOM and parent element. section 12.4 section 7.3
Listing 12.7 The application instance (app.js)
import { mountDOM } from './mount-dom'
import { destroyDOM } from './destroy-dom'
import { h } from './h'
export function createApp(RootComponent, props = {}) { #1
let parentEl = null
let isMounted = false
let vdom = null
function reset() { #2
parentEl = null
isMounted = false
vdom = null
}
return {
mount(_parentEl) {
if (isMounted) { #3
throw new Error('The application is already mounted')
}
parentEl = _parentEl #4
vdom = h(RootComponent, props) #5
mountDOM(vdom, parentEl) #6
isMounted = true
},
unmount() {
if (!isMounted) { #7
throw new Error('The application is not mounted')
}
destroyDOM(vdom) #8
reset() #9
},
}
}
The complete application-instance implementation shows parent-element storage, root-component creation, DOM mounting, duplicate-mount protection, unmounting, and lifecycle reset. section 12.4
