3.4. Getting Started with VMx — TypeScript¶
This tutorial walks you through building viewmodels with the VMx TypeScript
library. You will build a ComponentVMOf<UserModel>, a RelayCommand with a
reactive trigger, and a tab composite with tab selection — all in a Node
script or test. The code blocks form one program in page order. Option A and Option B
of section 3.4.2 are alternatives, and the later blocks use the hub and dispatcher
of Option A.
For the contracts behind each type, see the component family, command families, and composite family.
Moving an existing app from an older VMx line? Start with Upgrading TypeScript and React Consumers.
3.4.1. Install¶
Add VMx as described in Installation. The TypeScript
section of that page covers the npm package and an unreleased source line. @thekaveh/vmx
ships dual ESM and CJS bundles with full TypeScript declarations, so no
@types package is needed.
To start a new Node project without a UI, use the TypeScript Node starter template in
starters/typescript-node/. It was verified against@thekaveh/vmx3.30.0 from npm. From a VMx checkout, runpython3 tools/create-starter.py. The command writes the project to a new directory outside the checkout, installs the exact npm version and runs the starter's smoke test.
3.4.2. Wire Up MessageHub And RxDispatcher¶
The viewmodels in this tutorial need two services: a hub that carries messages between viewmodels and a dispatcher that knows about your scheduler pair.
3.4.2.1. Option A — Immediate (Node Scripts / Synchronous Tests)¶
import { MessageHub, RxDispatcher } from "@thekaveh/vmx";
const hub = new MessageHub();
const dispatcher = RxDispatcher.immediate();
// Both foreground and background use queueScheduler (synchronous).
// Safe for Node scripts and vitest suites with no async event loop.
3.4.2.2. Option B — Custom Schedulers (Browser / Async Environments)¶
import { asapScheduler, asyncScheduler } from "rxjs";
// `RxDispatcher` is imported in Option A. A UI application passes this
// dispatcher to its viewmodels instead of `dispatcher`.
const uiDispatcher = new RxDispatcher(
asapScheduler, // foreground — UI thread, microtask queue
asyncScheduler, // background — macro-task queue
);
Do not use animationFrameScheduler as the foreground scheduler. Browsers pause
requestAnimationFrame callbacks in hidden tabs, so a background view-model
stays Constructing while its tab is hidden.
3.4.3. Build A ComponentVMOf<UserModel>¶
ComponentVMOf<M> is the primary leaf viewmodel. It holds a typed model, fires
PropertyChangedMessage on the hub when the model changes, and participates in
the lifecycle state machine
(Destructed → Constructing → Constructed → Destructing → Destructed).
import { ComponentVMOf, isPropertyChanged } from "@thekaveh/vmx";
interface UserModel {
name: string;
email: string;
}
// Build the viewmodel — every builder setter returns a NEW builder (immutable).
const userVM = ComponentVMOf.builder<UserModel>()
.name("user-card")
.model({ name: "Alice", email: "alice@example.com" })
.services(hub, dispatcher)
// Derive a display hint from the model.
.modeledHinter((m) => m.name)
// Optional callbacks.
.onConstruct(() => console.log("user-card constructed"))
.onDestruct(() => console.log("user-card destructed"))
.build();
// Subscribe to hub messages BEFORE constructing.
hub.messages.subscribe((msg) => {
if (isPropertyChanged(msg, { sender: userVM })) {
console.log(`Property '${msg.propertyName}' changed on ${msg.senderName}`);
}
});
// construct() transitions Destructed → Constructing → Constructed.
userVM.construct();
// stdout: "user-card constructed"
// Update the model.
userVM.model = { name: "Alice Smith", email: "asmith@example.com" };
// stdout: "Property 'model' changed on user-card"
// stdout: "Property 'modeledHint' changed on user-card"
console.log(userVM.modeledHint); // "Alice Smith"
console.log(userVM.isConstructed); // true
See the component family for the full component contract and Services, Messages & Dispatching for the
PropertyChangedMessageschema.
3.4.4. Build A RelayCommand¶
RelayCommand wraps an optional execute callback, an optional canExecute
predicate, and a set of RxJS Observable triggers that signal canExecute may
have changed.
import { Subject } from "rxjs";
import { RelayCommand } from "@thekaveh/vmx";
const canSaveTrigger = new Subject<void>();
let isDirty = false;
const saveCommand = RelayCommand.builder()
.task(() => {
console.log("Saving…");
isDirty = false;
canSaveTrigger.next(); // re-evaluate canExecute
})
.predicate(() => isDirty)
.triggers(canSaveTrigger)
.build();
console.log(saveCommand.canExecute()); // false
isDirty = true;
canSaveTrigger.next(); // fires canExecuteChanged
saveCommand.canExecuteChanged.subscribe(() =>
console.log(` canExecute is now ${saveCommand.canExecute()}`)
);
console.log(saveCommand.canExecute()); // true
saveCommand.execute();
// stdout: "Saving…"
// stdout: " canExecute is now false" (the task fires the trigger)
console.log(saveCommand.canExecute()); // false again
// Dispose to unsubscribe all trigger subscriptions. Disposal sends one final
// canExecuteChanged notification before it completes the stream.
saveCommand.dispose();
// stdout: " canExecute is now false"
See command families for the full command contract.
3.4.5. Build A Tab Composite¶
CompositeVM<VM> owns an ordered child collection and a current selection
slot. Children are provided by a factory that runs on the first construct()
call.
import { CompositeVM, whenPropertyChanged } from "@thekaveh/vmx";
interface TabModel {
title: string;
}
const tab1 = ComponentVMOf.builder<TabModel>()
.name("home-tab")
.model({ title: "Home" })
.services(hub, dispatcher)
.build();
const tab2 = ComponentVMOf.builder<TabModel>()
.name("settings-tab")
.model({ title: "Settings" })
.services(hub, dispatcher)
.build();
const tabs = CompositeVM.builder<ComponentVMOf<TabModel>>()
.name("tab-bar")
.services(hub, dispatcher)
.children(() => [tab1, tab2])
.onConstruct(() => console.log("tab-bar constructing"))
.build();
// Watch for current-selection changes via the hub.
whenPropertyChanged(hub, tabs, "current").subscribe(() => {
const title = tabs.current ? tabs.current.model.title : "(none)";
console.log(`Selected tab: ${title}`);
});
// The hook runs while the composite is Constructing. Each child then
// constructs, and the composite becomes Constructed after the last child.
tabs.construct();
// stdout: "tab-bar constructing"
// Select a tab — publishes PropertyChangedMessage for "current" and
// sets child.isCurrent.
tabs.current = tab2; // stdout: "Selected tab: Settings"
tabs.current = tab1; // stdout: "Selected tab: Home"
console.log([...tabs].map((c) => c.name)); // ["home-tab", "settings-tab"]
console.log(tab2.isCurrent); // false
See the composite family for the full
CompositeVMcontract, includingCollectionChangedEventandBatchUpdatesemantics.
3.4.6. Lifecycle And Cleanup¶
The VMs in this tutorial have five lifecycle states. Four of them form a
reversible cycle, Destructed → Constructing → Constructed → Destructing → Destructed. The fifth state, Disposed, is terminal.
import { ConstructionStatus } from "@thekaveh/vmx";
console.log(userVM.status); // 4 (ConstructionStatus.Constructed)
// reconstruct() is destruct() + construct() in a single call. It is only valid
// from Constructed (canReconstruct() is true iff status === Constructed); it
// round-trips through Destructed and back to Constructed.
userVM.reconstruct();
console.log(userVM.status); // 4 (ConstructionStatus.Constructed)
// destruct() transitions back to Destructed and runs onDestruct.
userVM.destruct();
console.log(userVM.status); // 2 (ConstructionStatus.Destructed)
// dispose() is terminal and idempotent. Calling construct() or destruct()
// on a disposed VM raises StatusTransitionError.
userVM.dispose();
console.log(userVM.status); // 0 (ConstructionStatus.Disposed)
// CompositeVM.dispose() disposes children, then itself.
tabs.dispose();
Dispose the hub last, after every viewmodel that uses it. MessageHub.dispose()
completes the underlying Rx subject. The later sections still use the hub, so
the full shutdown sequence appears at the end of section 3.4.9.
See Lifecycle & Messaging for the transition table, the error of a refused operation, and the callback ordering.
3.4.7. Threading¶
RxDispatcher pairs two RxJS schedulers:
| Scheduler | Typical mapping |
|---|---|
dispatcher.foreground |
UI thread / asapScheduler |
dispatcher.background |
asyncScheduler / worker threads |
All hub observations delivered on foreground are safe to bind to UI controls.
Use observeOn from rxjs to marshal:
import { isPropertyChanged, type PropertyChangedMessage } from "@thekaveh/vmx";
import { filter, observeOn } from "rxjs";
// Stub for your UI code: replace it with the label update.
const updateLabel = (msg: PropertyChangedMessage<unknown>): void => console.log(msg.propertyName);
hub.messages.pipe(
filter(isPropertyChanged),
observeOn(dispatcher.foreground), // marshal to UI scheduler
).subscribe((msg) => updateLabel(msg));
See Services, Messages & Dispatching for the foreground rules for property and collection changes.
3.4.8. Test Viewmodels Without Runner-Specific Fixtures¶
The @thekaveh/vmx/testing subpath supplies hermetic services and semantic
recorders without importing Vitest or Jest:
import { expect } from "vitest";
import { createTestServices, recordPropertyChanges } from "@thekaveh/vmx/testing";
const services = createTestServices();
// The recorder observes services.hub, so build the VM under test on it.
const testVM = ComponentVMOf.builder<UserModel>()
.name("user-card")
.model({ name: "Alice", email: "alice@example.com" })
.services(services.hub, services.dispatcher)
.build();
testVM.construct();
const changes = recordPropertyChanges(services.hub, {
sender: testVM,
propertyName: "model",
});
testVM.model = { name: "Updated", email: "updated@example.com" };
expect(changes.records).toHaveLength(1);
changes.dispose();
testVM.dispose();
services.dispose();
The subpath requires @thekaveh/vmx 3.30.0 or later.
Runner-Neutral Testing Support
describes the other helpers, such as ManualDispatcher, the command doubles,
and createFormHarness().
3.4.9. Observe A Hub Safely¶
Use the optional DevTools subpath when development diagnostics need a message log or an explicit state snapshot:
import { connectReduxDevtools } from "@thekaveh/vmx/devtools";
const editorVM = ComponentVMOf.builder<UserModel>()
.name("user-editor")
.model({ name: "Alice", email: "alice@example.com" })
.services(hub, dispatcher)
.build();
const devtools = connectReduxDevtools(hub, {
name: "user-editor",
snapshots: [
{
name: "user",
select: () => ({ name: editorVM.model.name }),
},
],
throttleMs: 16,
onError: (error, context) => console.warn(context.phase, error),
});
// The owning adapter controls this lifetime.
devtools.dispose();
VMx does not serialize the message sender or model graph by default. Add only the named snapshots that the diagnosis needs. DevTools Observability describes redaction, filters, throttling, and the limits of the bridge.
At shutdown, dispose the viewmodels first and the hub last:
editorVM.dispose();
hub.dispose();
3.4.10. Where To Go Next¶
| Resource | Documentation page |
|---|---|
| Specification status | Specification & Conformance |
| Lifecycle contract | Lifecycle & Messaging |
| Messages & threading | Services, Messages & Dispatching |
| Commands | Command Families |
| Component contract | Component Family |
| Composite contract | Composite Family |
| Builders & tree | Builders, Collections & Tree Utilities |
| Architecture | Architecture Map |
| TypeScript status | TypeScript Flavor |
| Examples | Smaller Examples |