Guides
Architecture patterns
Patterns for building full applications with mx.js, from single-file sites to large-scale SPAs.
Single idea at every scale#
Every pattern you see here is the same idea applied. Something happens, you change plain variables, you push the new state to the components that show it, and render() writes only what changed without the need for store, subscriptions or dependency graphs.
- EventClick, feed tick, route
- Update statePlain variables, in place
- .$()Push state to components
- render()Writes only what changed
The shell sets up the components once, and updateAll() pushes new state to them. The attribute cache is what keeps pushing to every component cheap. Everything else here (events, routing, views, feeds, SSG) decides where an update starts and which container it renders into.
App shell#
Every mx app starts with a shell. It renders the layout once, keeps persistent references and wires up events.
// 1. Render the app shell
let app = document.getElementById('app');
app.render(
mx('sidebar-nav', { currentPath: '/' }),
mx.div({ id: 'main' }),
mx('player-bar')
);
// 2. Get persistent references to shell components
let sidebar = app.querySelector('sidebar-nav');
let mainContent = app.querySelector('#main');
let playerBar = app.querySelector('player-bar');
// 3. Wire cross-component events
events.on('track:play', data => {
playerBar.$({ track: data.track, isPlaying: true, progress: 0 });
});
// 4. Navigate to initial route
navigate(location.pathname);The shell components (sidebar-nav, player-bar) are created once and updated via .$(). The #main container swaps its content on navigation. Every mx SPA is built on top of this.
The update-all pattern#
For apps with many components sharing state (dashboards, real-time feeds), use a single updateAll() function that pushes derived state to every component:
let selectedAssetId = null;
let activeSector = null;
function updateAll() {
let derived = computeDerived();
let filtered = getFilteredAssets();
// Push state to all components in one pass
ticker.$({ assets: ASSETS });
watchlist.$({ assets: filtered, selectedId: selectedAssetId });
priceChart.$({ asset: assetById(selectedAssetId) });
kpiValue.$({ value: derived.portfolioValue, label: 'Portfolio' });
movers.$({ gainers: derived.gainers, losers: derived.losers });
}
// Everything funnels through updateAll
feed.on(updateAll);
events.on('asset:select', id => { selectedAssetId = id; updateAll(); });
events.on('filter:sector', s => {
activeSector = activeSector === s ? null : s;
updateAll();
});This scales to 10+ components without getting complicated. You compute derived values once and push them to every component with plain function calls, so there is no dependency tracking or subscription to manage.
Signals add implicit dependencies. updateAll() is explicit, so you see exactly what updates and when. On dashboards with 50ms data feeds, that explicitness prevents cascade bugs.
How the attribute cache keeps pushing cheap#
updateAll() calls .$() on every component on every tick, which re-renders each component's whole subtree. That sounds wasteful, and in a virtual-DOM framework the diff cost would scale with the tree. In mx it doesn't, because render() keeps a per-element cache of the attributes it last set and skips the DOM entirely for anything that hasn't changed.
// Render the same description twice. The second pass touches the DOM
// for nothing - every attribute already matches the cache.
row.render(mx.div({ class: 'cell', title: name }, name));
row.render(mx.div({ class: 'cell', title: name }, name)); // 0 setAttribute calls
// Change one thing, and only that one thing is written:
row.render(mx.div({ class: 'cell', title: name }, name));
row.render(mx.div({ class: 'cell active', title: name }, name));
// -> a single setAttribute('class', ...). title and the text node are untouched.mx still walks the description and compares values on every render, but a comparison is only a property read and an === check, which takes a few nanoseconds. What it avoids is the expensive part, the setAttribute or property write that makes the browser recompute layout and style.
What the cache looks like
Every plain element mx renders from a description carries one hidden object - the values it last applied - stored under an engine-private Symbol key, and the same cache drives handler and property cleanup. Component elements get their attributes through $() instead, so they have no cache:
// After a render, each element carries a small private cache of what mx set,
// stored under an engine-private Symbol key (invisible to your code):
// el[store] last-applied values e.g. { class: 'cell', title: 'Ada', onclick: fn, '.open': true }
//
// The cache is a null-prototype object, so a key named toString or constructor
// is just a key. It is the only record of the previous description: any key it
// holds that the new description no longer names is undone first (attribute
// removed, handler nulled, .prop nulled), then the children reconcile, then the
// new description is applied.
//
// Next render, for every incoming attribute mx does:
// if (value === cache[key]) continue; // already correct -> skip the DOM
// else { setAttribute / set property; cache[key] = value; }
// Two exceptions: a '.prop' key compares against the element's current
// property (so a user edit is overwritten), and value / checked / selected
// re-sync the property even on a cache hit.
//
// The comparison is a property read and an === check: a few nanoseconds.
// A setAttribute that the browser turns into a style invalidation is far
// more expensive - so the cache trades cheap JS for avoided browser work.Before mx 1.3.2 this store hung off el._$ / el._$$ as plain expandos - visible in devtools, and corruptible by user properties literally named ._$ or ._$$ (a destroyed cache leaked stale attributes and handlers). The Symbol key makes that collision impossible. You never maintain any of this yourself. It's how the reconciler keeps track of what the DOM already holds.
Why skipping setAttribute matters so much
A setAttribute does more than write a property. It tells the browser the element might look different, so the element gets marked style-dirty and its styles get recomputed on the next recalc. When mx skips the write because the value is unchanged, the browser is never told anything changed and never recalculates that element's style. The cache is less about saving JavaScript time than about keeping work off the browser's critical path.
What the measurements show
The reconciler's cost lies in the tree walk rather than the mutations, which is why mx scales flat. Re-rendering a subtree where one leaf changed costs essentially the same as one where five hundred leaves changed. The walk is identical, and the cache absorbs the difference at the DOM boundary. (The deep-tree numbers are in the benchmark write-ups. In short, mx is O(tree) and the tree walk is cheap.)
Handlers clean themselves up too
The same cache handles event handlers. Each render records the handlers it sets. A handler present last render and absent this one is nulled before the children reconcile. That's why you never manually remove a handler set through a render description, and why re-rendering can't stack listeners. (Handlers you add to document/window yourself are a different matter - see Lifecycle.)
Because no-op renders are nearly free, wrapping components in memoization usually adds bookkeeping that costs more than the render it "saves". Measure before you cache, and expect the measurement to say don't. See What mx Is Not → No Memoization.
Event bus#
The event bus keeps its registry in a Map and stores unique listeners in a Set.
Components communicate upward via callback props. For cross-component coordination (sibling → sibling, or any → app), use an event bus:
let events = (() => {
let listeners = new Map;
return {
send(event, data) {
listeners.get(event)?.forEach(fn => fn(data));
},
on(event, fn) {
let s = listeners.get(event);
s ? s.add(fn) : listeners.set(event, new Set([fn]));
return () => listeners.get(event)?.delete(fn);
}
};
})();
// Component fires event
mx.button({ onclick: () => events.send('asset:select', asset.id) }, 'Select asset');
// App listens and orchestrates
let unsubscribe = events.on('asset:select', id => {
selectedAssetId = id;
updateAll();
});
// The app owner calls unsubscribe() before disposing this subscription.Some common events from production:
| Event | Data | Fired by | Handled by |
|---|---|---|---|
| asset:select | id | Table row, card click | App → updateAll |
| filter:sector | sectorId | Filter pill | App → updateAll |
| track:play | { track } | Play button | App → playerBar.$() |
Routing#
There are two approaches, depending on how complex the app is:
Navigation API (modern SPA)
The Navigation API lets the router intercept navigation and update the current view.
let routes = { '/': 'home', '/contact': 'contact' };
let disposeView = () => {};
function navigate(path) {
let view = routes[path] || 'not-found';
navbarEl.$({ path });
window.scrollTo(0, 0);
disposeView();
disposeView = views[view].init(contentEl) || (() => {});
}
// Navigation API (modern SPA)
navigation.addEventListener('navigate', e => {
let url = new URL(e.destination.url);
if (!e.canIntercept || e.hashChange || e.downloadRequest != null || url.origin !== location.origin) return;
e.intercept({ handler: () => navigate(url.pathname) });
});Lazy-loaded views
For larger apps, load view scripts on demand:
// Integration: views is a registry; parseRoute returns an allowlisted view name.
// contentEl is owned by this router. init(container) returns a synchronous disposer.
let pendingViews = new Map();
function loadView(name) {
if (views[name]) return Promise.resolve();
if (pendingViews.has(name)) return pendingViews.get(name);
let promise = new Promise((resolve, reject) => {
// Existing SSG scripts must finish before the router starts. Do not poll forever.
let script = document.createElement('script');
script.src = '/views/' + encodeURIComponent(name) + '.js';
let timer = setTimeout(() => finish(new Error('View load timed out')), 15000);
function finish(error) {
clearTimeout(timer);
script.onload = script.onerror = null;
script.remove();
if (error) reject(error); else resolve();
}
script.onload = () => finish(views[name] ? null : new Error('View did not register'));
script.onerror = () => finish(new Error('View download failed'));
document.head.append(script);
});
pendingViews.set(name, promise);
promise.catch(() => pendingViews.delete(name)); // Permit retry after failure.
return promise;
}
let routeGeneration = 0;
let disposeView = () => {};
async function navigate(path) {
let mine = ++routeGeneration;
disposeView();
disposeView = () => {};
contentEl.render(mx.p({ role: 'status' }, 'Loading view...'));
try {
let name = parseRoute(path);
await loadView(name);
if (mine !== routeGeneration) return;
disposeView = views[name].init(contentEl) || (() => {});
} catch (error) {
if (mine !== routeGeneration) return;
contentEl.render(mx.p({ role: 'alert' }, 'Could not load view'),
mx.button({ onclick: () => navigate(path) }, 'Retry'));
}
}
function disposeRouter() { ++routeGeneration; disposeView(); disposeView = () => {}; }What the router guarantees
- Views register in
views. Eachinit(container)returns a disposer. - Navigation disposes the old view immediately, and the generation check prevents a late script from replacing the current route.
- Call
disposeRouter()when removing the shell. - Dynamic script downloads cannot reliably be aborted, so obsolete completions are ignored.
View pattern#
An AbortController lets the view cancel a request when it is replaced.
Each view initialization owns its request, state, and render function. Its disposer aborts pending work and invalidates late completions:
// Integration: register in views; api.goals accepts { signal } (API Layer below).
views.dashboard = (() => {
function init(container) {
let generation = 0;
let controller;
let disposed = false;
let goals = [], state = 'loading';
function render() {
if (disposed) return;
container.render(
state === 'loading' ? mx.p({ role: 'status' }, 'Loading goals...') :
state === 'error' ? mx.div(mx.p({ role: 'alert' }, 'Could not load goals'),
mx.button({ onclick: load }, 'Retry')) :
!goals.length ? mx.div({ class: 'empty' }, 'No goals yet') :
mx.div({ class: 'grid' }, ...goals.map(goal => mx.article(goal.title)))
);
}
async function load() {
if (disposed) return;
let mine = ++generation;
controller?.abort();
controller = new AbortController();
state = 'loading'; render();
try {
let data = await api.goals({ signal: controller.signal });
if (disposed || mine !== generation) return;
goals = data; state = 'ready';
} catch (error) {
if (disposed || mine !== generation || error.name === 'AbortError') return;
state = 'error';
}
render();
}
load();
return () => { disposed = true; ++generation; controller.abort(); };
}
return { init, hydrate: init };
})();Loading, failure, empty results and populated results are each their own state. Retry starts a new generation, and disposal makes every pending completion inert. The router above calls the returned disposer before another view owns the container.
Static HTML with templates
For static sites (no dynamic data), use <template> elements instead of JS rendering. The content ships in the HTML, needs no JS rendering code, and cloning it is a single native call. Template content stays inert until the script clones it, so for content that should paint and be indexed before any script runs, use static site generation. A template setup looks like this:
<!-- Static HTML in <template> tags -->
<template id="v-home">
<section class="hero">
<h1>We build <span id="hero-rotate">small, powerful</span>
web applications.</h1>
<a href="/contact" class="btn">Get in Touch</a>
</section>
<footer>...</footer>
</template>
<script>
function navigate(path) {
let view = routes[path] || 'not-found';
navbarEl.$({ path });
// Clone static template into content area
let tpl = document.getElementById('v-' + view);
contentEl.textContent = '';
contentEl.append(tpl.content.cloneNode(true));
// Wire up SPA links on the cloned content
contentEl.querySelectorAll('a[href^="/"]').forEach(a => {
a.onclick = e => {
e.preventDefault();
navigation.navigate(a.getAttribute('href'));
};
});
}
</script>Real-time data#
For live data (WebSocket, polling, simulated feeds), mutate objects in place and push to components:
let feed = (() => {
let listeners = new Set;
let interval;
function tick() {
let count = 2 + Math.floor(Math.random() * 4);
let seen = new Set;
for (let i = 0; i < count; i++) {
let asset = ASSETS[Math.floor(Math.random() * ASSETS.length)];
if (seen.has(asset.id)) continue;
seen.add(asset.id);
// Mutate in place - no cloning
asset.price += (Math.random() - 0.5) * asset.price * 0.002;
asset.history.push(asset.price);
if (asset.history.length > 60) asset.history.shift();
}
listeners.forEach(fn => fn());
}
return {
start() { interval = setInterval(tick, 50); },
stop() { clearInterval(interval); },
on(fn) { listeners.add(fn); },
off(fn) { listeners.delete(fn); }
};
})();
// Wire to app - feed mutates data, updateAll pushes to components
feed.on(updateAll);
feed.start();Key principles
- Mutate in place - don't clone objects. Components read latest values on render.
- Deduplicate per tick - each item updated at most once per cycle.
- Cap history - prevent unbounded memory growth.
Frame-coalesced updates
When the feed fires faster than the screen refreshes, coalesce updates to one render per animation frame with requestAnimationFrame():
// Coalesce rapid updates into one render per frame
function rafThrottle(fn) {
let scheduled = false;
return () => {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
fn();
});
};
}
// Feed fires 20x/sec, but UI renders at most once per frame
let scheduleUpdate = rafThrottle(updateAll);
feed.on(scheduleUpdate);React and Vue batch updates made in the same task, but neither limits rendering to one per frame, so a fast feed needs the same throttle there. With mx you decide whether to do it per component or at the app level.
API layer#
Wrap fetch in a thin API client with auth handling:
let api = (() => {
let base = window.API_BASE || '';
async function request(path, options = {}) {
let { method = 'GET', body, signal } = options;
let opts = { method, signal, credentials: 'include', headers: {} };
if (body) {
opts.headers['content-type'] = 'application/json';
opts.body = JSON.stringify(body);
}
let res = await fetch(base + path, opts);
if (res.status === 401) {
auth.user = null;
navigation.navigate('/login');
throw new Error('Unauthorized');
}
let data = res.status === 204 ? null : await res.json().catch(_ => null);
if (!res.ok) throw new Error(data?.error || 'Request failed');
return data;
}
return {
me: () => request('/api/auth/me'),
goals: (options = {}) => request('/api/goals', options),
goal: slug => request('/api/goals/' + slug),
createGoal: data => request('/api/goals', { method: 'POST', body: data }),
};
})();Keep it simple: credentials for cookies, JSON in/out, 401 redirect. Add methods as you need them.
Lazy-loaded components#
When a component wraps a heavy external library (CodeMirror, chart engine, map SDK), lazy-load the library and defer rendering until it's ready:
// Integration: loadCodeMirror() resolves the CodeMirror factory (or rejects).
// The parent owns the editor and must call the returned disposer before removal.
async function mountEditor(host, { value = '', onChange } = {}, signal) {
let disposed = false;
let editor;
let area = dom.textarea({ 'aria-label': 'Code', '.value': value });
host.render(area);
function dispose() {
if (disposed) return;
disposed = true;
signal?.removeEventListener('abort', dispose);
editor?.toTextArea(); // Releases CodeMirror-owned DOM and handlers.
}
if (signal?.aborted) { dispose(); return dispose; }
signal?.addEventListener('abort', dispose, { once: true });
try {
let CodeMirror = await loadCodeMirror();
if (disposed || !host.isConnected) { dispose(); return dispose; }
editor = CodeMirror.fromTextArea(area, { lineNumbers: true, mode: 'javascript' });
editor.on('change', () => { if (!disposed) onChange?.(editor.getValue()); });
} catch (error) {
if (!disposed) {
// The textarea remains usable if loading fails.
host.append(dom.p({ role: 'alert' }, 'Editor could not load; plain text remains available.'));
}
}
return dispose;
}
// Mount with an AbortController owned by the current route. Abort even while
// the promise is pending; after resolution the returned function also disposes.
// Do not render over host while CodeMirror owns it; mount a fresh editor on reentry.Key patterns
AbortSignal- owner cancels even while the library is loadingdispose()- releases editor resources before the route is removedisConnected- avoids creating an editor in a detached host- Keep the editor host outside parent reconciliation while the library owns its children.
Static site generation#
mx's reconciler walks existing DOM children. If the HTML is already in the page (from SSG, hand-written markup, or server render), mx takes over and reuses its nodes instead of re-creating them, which we call parasitic hydration:
// Build step: pre-render with happy-dom (no browser needed)
import fs from 'node:fs';
import { Window } from 'happy-dom';
let window = new Window({ url: 'https://example.com' });
let { document } = window;
// Load mx.js globals into the fake DOM environment
window.eval(fs.readFileSync('ui-mx.min.js', 'utf8'));
// Load components
window.eval(fs.readFileSync('components/navbar.js', 'utf8'));
// Your app setup must also register window.views.home before the next line.
// Render a view
let container = document.createElement('div');
window.views.home.init(container);
// Output static HTML
let html = container.innerHTML;
fs.writeFileSync('dist/index.html', wrapInShell(html));
// mx's reconciler reuses existing DOM on client load
// - no hydration markers needed, just structurally matching HTML
// (innerHTML has no whitespace between tags, so every node lines up)The reconciler compares the existing child at each position with the description, reuses it when the tag matches and replaces it when it doesn't, so you don't need hydration markers, data-reactroot or a client/server contract. Whitespace between tags counts as a child too, so formatted HTML has to be minified first, and an attribute that only the server HTML carries stays until the description names it (see What the server HTML needs).
Upgrading server-rendered custom elements#
For plain HTML elements the reconciler handles everything, so the SSR'd <div> becomes the live <div> and mx patches its attributes from there. Custom elements (<my-navbar>, <goal-card>) need one extra step: the element exists in the DOM, but doesn't yet have the methods from define() attached. Until you attach them, .$() is undefined.
mx attaches methods inside createElement - it does Object.assign(element, components[tag]) on every fresh node. Server-rendered elements weren't created by mx, so they need a one-time upgrade pass after the define() calls have run:
// In your app entry point, after all define() calls have executed:
document.querySelectorAll(Object.keys(components)).forEach(el =>
!el.$ && Object.assign(el, components[el.localName]));The array gets implicitly stringified to a comma-separated selector list - querySelectorAll coerces its argument to DOMString via the WebIDL spec, which calls Array.prototype.toString (i.e. join(',')). That means one pass over the DOM and one lookup per element by localName.
After this pass every server-rendered custom element has $ and any other methods from its definition ($attrs is on every element already), and from then on it behaves identically to one created via mx.
When to call .$() afterwards
Some upgraded elements need to render with current state, like the navbar showing the logged-in user or the goal card showing live progress. For those, call .$(state) explicitly after the upgrade:
navbarEl.$({ path: location.pathname, user: currentUser });For static elements (footer, terms-link, anything whose appearance doesn't depend on runtime state) the SSR'd HTML is already correct, so no .$() call is needed. The methods are attached and will respond if you ever call them later, but their initial paint is whatever the server emitted.
If your SSR'd HTML doesn't use any custom elements - everything is plain <div>/<span>/<a>, skip the upgrade pass entirely. The reconciler handles plain elements without help, and custom elements only need the upgrade because they have methods that exist outside the HTML.
The pattern only iterates the registry and matches it against the DOM, with nothing hidden in the framework. components is a global object whose keys are tag names, querySelectorAll finds matching elements and Object.assign transplants the methods. If you wrote those two lines yourself without ever reading this, you'd arrive at the same code. mx leaves the upgrade to you because it is trivial and you might want to customize when it runs (after auth check, after route resolution, lazily per-element on visibility).
Scaling to ∞ components#
mx.js scales to hundreds of components, and these are the patterns that make it work:
Concatenation keeps the build to joining files and stripping whitespace and comments, so the output is reproducible and stays readable once beautified. You can tell which function is which without source maps. If you choose ES modules, keep in mind that a bundler resolves paths and bare specifiers differently from the browser, which needs import maps for them.
A production app with 200+ components ships ~100KB JS + 50KB CSS (gzipped), while framework apps of similar scope typically ship 500KB-1MB+.