mount()
The mount() function creates an element from a spec and prepares it for insertion into the DOM.
Syntax
Section titled “Syntax”const ref = mount(spec)Parameters
Section titled “Parameters”spec
: An element spec created with el(), map(), match(), or other view modules.
Return value
Section titled “Return value”A NodeRef with:
element— The created DOM element (ornullfor fragments)dispose()— Cleanup function that removes the element and runs all cleanup callbacks
Description
Section titled “Description”mount() creates DOM elements from specs:
const spec = el('div')('Hello');const ref = mount(spec);
document.body.appendChild(ref.element);Disposal
Section titled “Disposal”Disposal removes the element and runs all cleanup callbacks.
const ref = mount(App());document.body.appendChild(ref.element);
// Later, when unmountingref.dispose();App pattern
Section titled “App pattern”A common pattern is to mount once at startup:
const App = () => el('div').props({ id: 'app' })( Header(), Main(), Footer() );
const app = mount(App());document.body.appendChild(app.element);Examples
Section titled “Examples”Basic mounting
Section titled “Basic mounting”const { el, mount } = svc;
const button = mount( el('button').props({ onclick: () => console.log('clicked') })('Click me'));
document.getElementById('root').appendChild(button.element);Conditional mounting
Section titled “Conditional mounting”let appRef = null;
const show = () => { if (appRef) return; appRef = mount(App()); document.body.appendChild(appRef.element);};
const hide = () => { if (!appRef) return; appRef.dispose(); appRef = null;};Multiple instances
Section titled “Multiple instances”const Widget = (name: string) => el('div').props({ className: 'widget' })(name);
// Mount multiple independent instancesconst widget1 = mount(Widget('First'));const widget2 = mount(Widget('Second'));
document.getElementById('sidebar').appendChild(widget1.element);document.getElementById('main').appendChild(widget2.element);With disposal tracking
Section titled “With disposal tracking”const refs: NodeRef[] = [];
const addItem = (text: string) => { const ref = mount(el('li')(text)); refs.push(ref); list.appendChild(ref.element);};
const clearAll = () => { refs.forEach(ref => ref.dispose()); refs.length = 0;};