-
Notifications
You must be signed in to change notification settings - Fork 0
Reactive Counters
Mubarrat edited this page Aug 8, 2025
·
1 revision
This document demonstrates how to build reactive counters using the reactive primitives and DOM builder functions provided by the library.
Create a simple reactive counter that updates the displayed count when incremented.
const count = observable(0);
const counterElem = $html.div(
$html.button({ onclick: () => count.value-- }, "-"),
$html.span(count),
$html.button({ onclick: () => count.value++ }, "+")
);
document.body.appendChild(counterElem);-
countis anobservableholding the numeric state. - Buttons modify
count.valuedirectly using++and--. - The
<span>child is a function that automatically re-renders whencountchanges.
You can create computed values to reflect derived state such as double count or status messages.
const doubleCount = (() => count() * 2).computed(count);
const status = (() => `Count is ${count()}`).computed(count);
const display = $html.div(
$html.span(cstr`Double: ${doubleCount}`),
$html.br,
$html.span(status)
);
document.body.appendChild(display);- Computed observables automatically update when dependencies change.
- Use
.computed()on a zero-argument function, passing dependencies as arguments.
Manage a list of counters reactively using arrayObservable.
const counters = arrayObservable([observable(0), observable(10)]);
const addCounter = () => counters.push(observable(0));
const countersList = $html.div(
counters.bind.map((countObs, idx) =>
$html.div(
$html.button({ onclick: () => countObs.value-- }, "-"),
$html.span(countObs),
$html.button({ onclick: () => countObs.value++ }, "+"),
$html.span(` (Counter #${idx + 1})`)
)
),
$html.button({ onclick: addCounter }, "Add Counter")
);
document.body.appendChild(countersList);- Each element in
arrayObservableis itself anobservable. - Modifications trigger reactive updates to the UI.
- Adding/removing counters automatically updates the rendered list.
- Use
.valuefor readable increments/decrements:count.value++. - Use
observablefor scalar values andarrayObservablefor reactive lists. - Use computed observables to derive data reactively.
- Pass observables or functions as children in DOM builders to enable automatic re-rendering.
- Avoid mutating observable values without notifying changes (always use provided APIs).
This example covers:
- Managing reactive state with
observableandarrayObservable. - Updating UI reactively using DOM builder functions.
- Creating derived state using
fn.computed. - Clear, readable state mutations using
.value.
Reactive counters are a simple yet powerful illustration of building responsive user interfaces with the reactive primitives and DOM builder functions.
If you need any assistance or clarification on contributing, feel free to reach out by creating an issue.
Thank you for considering contributing to the Dom-Builder library!