Chapter 13: Data binding and reactivity
The introduction frames data binding as keeping a Vanilla app’s interface synchronized with changing data in both directions, without a framework runtime.
After this chapter you will be able to
- Two-way interface synchronization. Explain that dynamic data binding keeps a Vanilla app’s interface in sync with changing data in both directions, without a framework runtime.
- Reactive state and effects. Explain that reactive programming keeps UI parts that depend on changing data updated predictably, and distinguish state, derived data, and effects.
- Two-way data binding flow. Explain that data binding connects state to the UI in both directions: changed data appears in the UI, and user interactions update state.
- Browser primitives for reactivity. Distinguish framework-provided binding syntax from the browser primitives available for building reactive behavior. Explain that frameworks bundle those primitives into an opinionated model, while Vanilla Web lets developers choose a smaller model for the page.
- Direct DOM binding flow. Explain how a state object and render function bind a DOM element to state, while button events change that state.
- Derived subtotal binding. Explain why the subtotal is computed from source values when rendering instead of stored separately in state.
- Explicit state and DOM flow. Explain how input events and a render function create an interactive interface without automatic two-way binding: input writes to state, and rendering reads state to update the DOM.
- Microtask render batching. Trace how scheduleRender(), queueMicrotask(), and renderQueued collapse several synchronous state writes into one render using the latest state.
- Data attribute binding rules. Explain how data-bind and data-bind-attr tell a JavaScript helper where to put values from a state object, including how dotted paths are read.
- Manual binding render pass. Trace what happens when renderBindings(document, state) runs and explain what must happen after state changes for the DOM to update.
- Template string escaping. Explain that template strings produce markup as a string that is inserted with innerHTML, so every interpolated value must be HTML-escaped, even a field expected to be numeric.
- Whole section replacement tradeoffs. Describe what replacing innerHTML does to existing DOM nodes and their state or listeners, and explain when template strings remain a practical choice versus using event delegation or another rendering approach.
- Template cloning for binding. Describe how to bind data with a <template>: define the markup once, clone it, and fill in text and attributes with DOM APIs. Explain the tradeoff with template strings.
- Shared state store purpose. Explain when an EventTarget-based store is useful and why it fits a Vanilla Web app.
- Immediate subscriber notification. Describe what subscribe() does when a listener is added and how that affects the listener's first invocation.
- Component subscription lifecycle. Trace how a web component receives a store, subscribes and cleans up, including what happens if it is moved in the DOM.
- Proxy traps and target access. Explain how a Proxy intercepts property reads and writes, and why code must use the proxy rather than the original object for traps to run.
- Nested proxy identity caching. Describe why nested objects need lazy wrapping and why those wrappers are cached.
- Signal values and dependencies. Explain what a signal is and how the subtotal binding updates when its inputs change.
- Small library for signals. Justify using a small signals library in production rather than implementing signal mechanics inside the application.
- Binding pattern selection. Explain why binding patterns are alternatives rather than stages every app must pass through, and describe when to choose a simple pattern, a shared store, or Proxy or signals.
- Disciplined Vanilla State Management. Explain why most Vanilla apps do not need a heavy state management library, and identify the common sources of state bugs named here.
- Canonical and derived state. Explain why each concern should have one source of truth and why computable values should usually be derived rather than stored separately.
- Explicit async UI statuses. Distinguish loading, ready, empty, and error states, including why a successful response with no records needs its own status. Explain the visibility gained from explicit state transitions.
- Batched renders and stale work. Explain why rendering should be batched during rapid interactions and why outdated asynchronous work should be canceled.
- Browser First Form Validation. Explain why forms should start with built-in browser validation and when custom validation is appropriate.
- Validation At Data Boundaries. Describe where incoming data needs validation and why network responses and restored storage should be parsed or normalized before the rest of the app uses them.
What it builds on
- Working with events (chapter 6) · Uses DOM events as the browser’s means of capturing user interaction.
- Custom properties with dataset (chapter 6) · Uses data-* attributes on DOM elements.
- The Need for Cloning Templates (chapter 8) · Cloning template content for reuse.
- Cleanup in disconnectedCallback() (chapter 9) · Assumes the custom-element lifecycle and cleanup in disconnectedCallback().
- AbortController and stale requests (chapter 12) · Reuses the AbortController cancellation primitive previously used with fetch().
- The states property (chapter 9) · Custom states exposed through the states property.
- Request lifecycle (chapter 12) · request lifecycle states
- Forms (chapter 3) · Accessible forms and their built-in semantics
Section by section
Introduction
The introduction frames data binding as keeping a Vanilla app’s interface synchronized with changing data in both directions, without a framework runtime.
- Two-way interface synchronization: Explain that dynamic data binding keeps a Vanilla app’s interface in sync with changing data in both directions, without a framework runtime.
Why it matters: This is the problem the chapter’s binding techniques are meant to address.
Key terms: dynamic data binding, Vanilla app, framework runtime
13.1 Reactive thinking
Defines reactive thinking as predictable updates to data-dependent UI, identifies state, derived data, and effects, and contrasts framework models with choosing a small Vanilla JavaScript pattern.
- Reactive state and effects: Explain that reactive programming keeps UI parts that depend on changing data updated predictably, and distinguish state, derived data, and effects.
Why it matters: These distinctions make it easier to see what should change when application data changes. - Vanilla pattern choice: Distinguish frameworks’ packaged reactive models from the Vanilla JavaScript approach of choosing a small pattern that fits the page.
Why it matters: The section frames reactivity as a practical idea rather than something tied to one framework.
Key terms: reactive programming, state, derived data, effects, frameworks, Vanilla JavaScript, small pattern
13.2 Data binding techniques
Introduces data binding as a two-way flow between state and the UI and explains why browser primitives can support it without a framework.
- Two-way data binding flow: Explain that data binding connects state to the UI in both directions: changed data appears in the UI, and user interactions update state.
Why it matters: These two directions are the basic behavior any binding technique must provide. - Browser primitives for reactivity: Distinguish framework-provided binding syntax from the browser primitives available for building reactive behavior. Explain that frameworks bundle those primitives into an opinionated model, while Vanilla Web lets developers choose a smaller model for the page.
Why it matters: It explains why keeping a UI in sync is possible in Vanilla Web without adopting a framework runtime.
Key terms: data binding, state, UI, reactivity, events, DOM, queueMicrotask(), Proxy, EventTarget
13.2.1 Direct DOM binding
This section shows how direct DOM binding connects state to displayed content and user events, and cautions against relying on element IDs as global variables.
- Direct DOM binding flow: Explain how a state object and render function bind a DOM element to state, while button events change that state.
Why it matters: It makes clear which code updates the display and which code changes the underlying state. - DOM ID global shortcut: Describe why using element IDs as global identifiers is convenient in short examples but fragile in larger code, and name the recommended alternative.
Why it matters: Explicit element queries avoid hidden dependencies on global names.
Key terms: state object, render function, state.count, data binding, id, window, document.getElementById, scoped queries
13.2.2 Derived bindings
This section explains how to compute a UI value from source state during rendering, alongside a direct DOM binding pattern and a naming collision in the example.
- Derived subtotal binding: Explain why the subtotal is computed from source values when rendering instead of stored separately in state.
Why it matters: Computing the subtotal from its source values keeps the displayed result consistent with the state. - Direct DOM synchronization: Describe how explicit JavaScript connects state and DOM elements, and why that pattern becomes harder to coordinate as an interface grows.
Why it matters: This explains both the simplicity of the example and the coordination cost of adding more bindings. - Subtotal helper naming collision: Explain why the sample calls its helper calcSubtotal rather than subtotal.
Why it matters: The distinct helper name prevents an assignment that appears valid but does not update the subtotal output.
Key terms: derived data, state, rendering, subtotal, Direct DOM binding, render function, event listeners, calcSubtotal, window.subtotal, <output id="subtotal">
13.2.3 A render function with queueMicrotask()
This section shows how a state object, form input, and a render function can make a small interface reactive, then uses queueMicrotask() to batch renders after synchronous state changes.
- Explicit state and DOM flow: Explain how input events and a render function create an interactive interface without automatic two-way binding: input writes to state, and rendering reads state to update the DOM.
Why it matters: You can reason about and debug each direction of an interactive update separately. - Form values as state: Describe when converting a form section to a plain object is a useful input-to-state step, and explain the exception for fields with repeated names.
Why it matters: The simple form-to-state approach stays useful when you account for fields that can have multiple values. - Microtask render batching: Trace how scheduleRender(), queueMicrotask(), and renderQueued collapse several synchronous state writes into one render using the latest state.
Why it matters: Batching avoids repeated DOM work when one operation changes several state properties. - Rendering schedule tradeoffs: Distinguish immediate rendering, microtask scheduling, timers, and requestAnimationFrame() for the uses described here.
Why it matters: Choosing a schedule lets you avoid redundant updates without delaying or mistiming visual work.
Key terms: state object, render function, input event, two-way binding, formData.getAll(name), Object.fromEntries(), plain object, repeated checkboxes, queueMicrotask(), scheduleRender()
13.2.4 Binding through data-* attributes
This section shows how small pages can use data-* attributes as visible binding markers, while explaining the helper’s manual updates, limits, and XSS risk.
- Data attribute binding rules: Explain how data-bind and data-bind-attr tell a JavaScript helper where to put values from a state object, including how dotted paths are read.
Why it matters: You can read the markup to see which state values will appear where. - Manual binding render pass: Trace what happens when renderBindings(document, state) runs and explain what must happen after state changes for the DOM to update.
Why it matters: It prevents you from expecting a state change to update the page by itself. - Small binding pattern limits: Justify when this data-* binding approach fits and when a template-based component or explicit rendering function is a better choice.
Why it matters: Keeping the helper small makes its bindings easy to see without forcing complex interfaces into a limited format. - Text based binding safety: Explain why the helper should write text rather than arbitrary innerHTML unless a trusted sanitizer is available.
Why it matters: A convenient binding helper should not turn state values into unsafe HTML.
Key terms: data-bind, data-bind-attr, readPath(), dotted path, state object, renderBindings(), rendering pass, reactive system, disabled attribute, <template>-based component
13.2.5 Binding with template strings
This section explains how template strings can render HTML, why interpolated values must be escaped, and when replacing markup is an acceptable tradeoff.
- Template string escaping: Explain that template strings produce markup as a string that is inserted with innerHTML, so every interpolated value must be HTML-escaped, even a field expected to be numeric.
Why it matters: A value that normally looks harmless can make string-based rendering unsafe if it is not escaped. - Whole section replacement tradeoffs: Describe what replacing innerHTML does to existing DOM nodes and their state or listeners, and explain when template strings remain a practical choice versus using event delegation or another rendering approach.
Why it matters: The rendering choice affects whether an update preserves the user’s place and the interface’s behavior.
Key terms: template strings, innerHTML, HTML-escaped, interpolated value, event delegation, DOM nodes
13.2.6 Binding with <template>
This section presents <template> as a binding approach that clones predefined HTML and fills it using DOM APIs.
- Template cloning for binding: Describe how to bind data with a <template>: define the markup once, clone it, and fill in text and attributes with DOM APIs. Explain the tradeoff with template strings.
Why it matters: It gives you a way to bind data while keeping the markup in HTML.
Key terms: <template>, template strings, DOM APIs
13.2.7 EventTarget stores
This section explains how an EventTarget-based store can share state across page components and how subscribers and web components manage subscriptions.
- Shared state store purpose: Explain when an EventTarget-based store is useful and why it fits a Vanilla Web app.
Why it matters: It gives independent parts of a page a shared state without requiring a framework store. - Immediate subscriber notification: Describe what subscribe() does when a listener is added and how that affects the listener's first invocation.
Why it matters: It explains why a subscription listener runs immediately, even when the state has not changed. - Component subscription lifecycle: Trace how a web component receives a store, subscribes and cleans up, including what happens if it is moved in the DOM.
Why it matters: Correct cleanup lets components move or disconnect without retaining stale subscriptions. - AbortSignal subscription cleanup: Describe the AbortController alternative for cleaning up a component's listeners and subscriptions.
Why it matters: One abort call can simplify cleanup when a component has multiple listeners.
Key terms: explicit store, EventTarget, shared state, subscribe(), listener, current state, change event, connectedCallback(), disconnectedCallback(), #unsubscribe
13.2.8 Proxy
This section explains how Proxy can make object property changes reactive, including nested state, and where the approach needs care.
- Proxy traps and target access: Explain how a Proxy intercepts property reads and writes, and why code must use the proxy rather than the original object for traps to run.
Why it matters: Changes cannot trigger proxy-based reactions if they bypass the proxy. - Reflect forwarding inside traps: Justify using Reflect.get() and Reflect.set() to forward operations inside production Proxy traps.
Why it matters: Forwarding through Reflect preserves ordinary property behavior while a trap intercepts it. - Nested proxy identity caching: Describe why nested objects need lazy wrapping and why those wrappers are cached.
Why it matters: Nested writes can trigger a rerender without sacrificing stable object references. - Proxy reactivity limits and batching: Describe the section’s cautions about Proxy-based state and how it handles redundant notifications and render bursts.
Why it matters: These limits help prevent missed updates and unnecessary renders in a small reactive state container.
Key terms: Proxy, target, handler, traps, get trap, set trap, Reflect.get(), Reflect.set(), shallow, WeakMap
13.2.9 Signals through a micro-library
This section explains how signals support reactive bindings, why a small library is the practical choice for production code, and how another emerging browser API relates to reactivity.
- Signal values and dependencies: Explain what a signal is and how the subtotal binding updates when its inputs change.
Why it matters: This explains how a displayed value can stay in sync with changing data without manually tracking every dependency. - Small library for signals: Justify using a small signals library in production rather than implementing signal mechanics inside the application.
Why it matters: A small library provides the reactive behavior without requiring a UI framework or maintaining error-prone mechanics yourself. - Observable API context: Distinguish the emerging Observable API from a broadly available built-in reactive primitive.
Why it matters: The example shows reactive ideas moving toward the platform without implying they are universally available yet.
Key terms: signal, effect, dependency tracking, subtotal.value, Signal class, @preact/signals-core, signal(), computed(), effect(), batch()
13.2.10 Choosing a binding pattern
This section gives criteria for choosing a data-binding pattern and shows how CSS can handle presentation when JavaScript reflects state into the DOM.
- Binding pattern selection: Explain why binding patterns are alternatives rather than stages every app must pass through, and describe when to choose a simple pattern, a shared store, or Proxy or signals.
Why it matters: The right pattern is the simplest one that addresses the app’s actual state and update needs. - CSS-driven state presentation: Describe how reflecting state into a DOM attribute or custom state lets CSS selectors control presentation instead of requiring JavaScript to update every affected element.
Why it matters: A state marker in the DOM can replace repeated JavaScript presentation updates with CSS rules.
Key terms: render functions, EventTarget-based stores, Proxy-based state, signals, explicit control, ergonomics, data-status, CustomStateSet, CSS selectors, :state()
13.3 State management
Explains why state management in most Vanilla apps is more about discipline than a heavy library.
- Disciplined Vanilla State Management: Explain why most Vanilla apps do not need a heavy state management library, and identify the common sources of state bugs named here.
Why it matters: It helps you look for the causes of state bugs before adding a state management library.
Key terms: state management library, state bugs, duplicated values, hidden side effects, asynchronous work, UI state
13.3.1 Design patterns
This section gives practical rules for keeping plain JavaScript UI state consistent, responsive, and easy to inspect.
- Canonical and derived state: Explain why each concern should have one source of truth and why computable values should usually be derived rather than stored separately.
Why it matters: Fewer independent values mean fewer opportunities for the UI and its data to disagree. - Explicit async UI statuses: Distinguish loading, ready, empty, and error states, including why a successful response with no records needs its own status. Explain the visibility gained from explicit state transitions.
Why it matters: Distinct statuses let the UI show the right message and make transitions easier to inspect. - State ownership and placement: Explain when to keep state near a DOM subtree and when a global store is appropriate.
Why it matters: Placing state near its owner avoids making local UI concerns unnecessarily global. - Batched renders and stale work: Explain why rendering should be batched during rapid interactions and why outdated asynchronous work should be canceled.
Why it matters: These rules prevent unnecessary renders and keep old responses from replacing newer results. - Timeout and cancellation distinction: Distinguish the rejection name for a timed-out request from AbortError and describe the choice the app must make about handling a timeout.
Why it matters: Distinguishing the rejection names prevents timeouts from being handled accidentally as ordinary cancellations.
Key terms: source of truth, Derive instead of duplicating, visibleItems, async state, loading, ready, empty, error, state transition, Co-locate state
13.4 Data validation
This section explains where to validate incoming data, why browser validation is the starting point for forms, and why network and stored data should be parsed before use.
- Browser First Form Validation: Explain why forms should start with built-in browser validation and when custom validation is appropriate.
Why it matters: Using the browser’s form features avoids unnecessary code and preserves built-in accessibility benefits. - Validation At Data Boundaries: Describe where incoming data needs validation and why network responses and restored storage should be parsed or normalized before the rest of the app uses them.
Why it matters: Checking data at the boundary keeps rendering code simpler and prevents old or damaged stored data from being assumed valid.
Key terms: built-in validation, required, type, minlength, pattern, checkValidity(), boundaries, normalize early, fail fast, parsing
13.5 Summary
Where this is used later
- Planning (chapter 15) · The book presents several data-binding techniques from which an app can choose.
- Basic tips (chapter 14) · Introduces a scheduled render function as a reactive binding pattern.
- Data flow and reactivity (chapter 15) · The EventTarget store pattern used for subscriptions.
Concepts explained in this chapter
- renderingRendering is the process of producing visible interface content from application data, state, or route information.
- signalA reactive value container that notifies dependent computations and effects when its value changes.
- stateData representing an application's current condition and behavior.
- data bindingDynamic data binding synchronizes changing application data with user-interface elements, potentially in both directions.
- reactive programmingReactivity is a programming model in which changes to data automatically propagate to dependent computations or interface output.
- data attributeA custom HTML attribute whose name begins with data- and whose value stores application-specific information on an element.
- AbortControllerAbortController is a browser interface for signaling cancellation of asynchronous operations such as fetch requests and event listeners.
- AbortSignalA web-platform interface that communicates cancellation of an asynchronous operation.
- connectedcallbackconnectedCallback is a custom element lifecycle callback that the browser invokes when the element is attached to a document DOM.
- vanilla webAn approach to building websites and web applications with core web technologies and browser APIs without a framework defining the application architecture.
- HTML template elementThe HTML <template> element holds inert markup that can later be cloned and inserted into a document or shadow DOM.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
