liveBook · Manning

createApp

As explained in Build a Frontend Web Framework (From Scratch)

A book-specific JavaScript function that creates an application instance from initial state and a top-level view.

createApp creates an application instance around initial state and a top-level view. The instance exposes mount(), which receives a DOM element and starts rendering there. section 5.2.2

The initial implementation separates a few small responsibilities:

  • Stores the mounting element in parentEl and the previous virtual DOM tree in vdom; both begin as null. section 5.2.2
  • Renders by destroying an existing DOM tree, calling view(state) to create a new virtual DOM tree, and mounting it. section 5.2.2
  • Keeps renderApp private while exposing mount() as the developer-facing application method. section 5.2.2

Initial application setup

createApp({ state, view }).mount(document.querySelector('#app')) creates the instance, remembers the parent element, evaluates the top-level view with state, and mounts its virtual DOM. section 5.2.2

Listing 5.5 The application instance with its renderer (app.js)
import { destroyDOM } from './destroy-dom'
import { mountDOM } from './mount-dom'

export function createApp({ state, view }) {     #1
  let parentEl = null
  let vdom = null

  function renderApp() {
    if (vdom) {
      destroyDOM(vdom)    #2
    }

    vdom = view(state) 
    mountDOM(vdom, parentEl)     #3
  }

  return {
    mount(_parentEl) {       #4
      parentEl = _parentEl
      renderApp()
    },
  }
}

The implementation listing shows how the closure variables, renderApp(), and mount() fit together in app.js. section 5.2.2

Later, the application instance becomes smaller: state moves into components, createApp receives a root component and optional props, and the returned instance adds unmount() with mount-state checks. section 12.4

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Implements closure state and a full initial render, then defers reactive state updates and later component-owned state.
Examples
Uses app.js implementation listings and a mounting call that renders a state-driven top-level view into a DOM element.
What it assumes
Assumes JavaScript functions, closures, DOM elements, virtual DOM trees, and existing mountDOM() and destroyDOM() helpers.
What you can do after
Builds a small application factory with mount(), rendering state through a top-level view into the DOM.
How it connects
Connects the application instance to the renderer, virtual DOM, state manager, components, and DOM mounting and destruction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.