Add Models
Walkthrough part 3: move your data into a schema-backed model and let views react to every change.
The spellbook works, but its data is a frozen array in a module: no way to change a spell, no validation, and no signal to other views when something changes. This part replaces app/lib/spells.js with a real model, and the app starts reacting on its own.
Define the model
Create app/models/spell.js. The schema is the single source of truth for what a spell is:
// app/models/spell.js
import { PuzzleModel, Puzzle } from '@magic-spells/puzzle';
export default class Spell extends PuzzleModel {
static schema = {
id: Puzzle.string().primary(),
name: Puzzle.string().required().min(1, 'A spell needs a name'),
school: Puzzle.string().oneOf(['Abjuration', 'Conjuration', 'Transmutation']),
level: Puzzle.number().min(1).max(9).default(1),
learned: Puzzle.boolean().default(false),
};
}Each field is a builder chain: a type, then modifiers. .primary() marks the lookup key, .required() rejects empty names at write time, .min(1).max(9) constrains levels, and .default(false) means new spells start unlearned without anyone saying so.
Register and seed
The app learns about models in app/app.js, and the same file is the right place to seed the store with our starting spells. The beforeMount hook runs once, before the first view mounts:
// app/models/index.js
import Spell from './spell.js';
export default { spell: Spell };
// app/app.js
import { PuzzleApp } from '@magic-spells/puzzle';
import routes from '@/routes.js';
import models from '@/models/index.js';
const SEED = [
{ id: 's1', name: 'Featherfall', school: 'Transmutation', level: 1 },
{ id: 's2', name: 'Mage Armor', school: 'Abjuration', level: 1 },
{ id: 's3', name: 'Misty Step', school: 'Conjuration', level: 2 },
{ id: 's4', name: 'Counterspell', school: 'Abjuration', level: 3 },
{ id: 's5', name: 'Polymorph', school: 'Transmutation', level: 4 },
];
const app = new PuzzleApp({
target: '#app',
routes,
models,
beforeMount({ store }) {
SEED.forEach((s) => store.createRecord('spell', s));
},
});
app.mount();
export default app;Every record passes through the schema on the way in: defaults fill (each spell gets learned: false), rules check, and an invalid seed throws instead of quietly corrupting your store. app/lib/spells.js is deleted; the array's job is done.
Seeding suits data that ships with the app. When spells come from an API instead, the model declares an endpoint and the same view code fetches them, with no seed at all; Data & Models shows how.
Query from the views
Both views drop their import of the old array and ask the store instead. In Spellbook.pzl:
// app/views/Spellbook.pzl: the script's data() only
data(params, props) {
const query = this.getData()?.query ?? '';
const needle = query.toLowerCase();
const spells = this.ctx.store
.findMany('spell')
.filter((s) => s.name.toLowerCase().includes(needle));
return { query, spells };
}And SpellDetail.pzl becomes a one-line lookup:
// app/views/SpellDetail.pzl: the script's data() only
data(params, props) {
return { spell: this.ctx.store.findOne('spell', params.id) };
}These aren't just reads. A store query inside data() subscribes the view: the list re-runs when the spell collection changes, and the detail view re-runs when its selected spell changes. Each mounted view then patches its output. You never wire that up; querying is subscribing.
The payoff: mutate and watch
Add a "learned" checkbox to each row in Spellbook.pzl:
{#for spell in spells}
<li key={ spell.id }>
<a href="{ link('/spells/' + spell.id) }"><strong>{ spell.name }</strong></a>
<span>{ spell.school } · level { spell.level }</span>
<label>
<input type="checkbox" checked={ spell.learned } /> learned
</label>
</li>
{/for}That checkbox has no handler. Its expression is a member path on a record, so the two-way binding writes through record.update(), validated by the schema, and the store notifies every subscribed view. Toggle a spell on the list, open its detail page, and the detail page is already correct: both views read the same record.
For richer writes, do the same thing from an event handler:
// template: <button @click={ toggleLearned(spell) }>toggle</button>
events = {
toggleLearned: (spell) => {
spell.update({ learned: !spell.learned });
// No refresh() needed: the store notifies every subscribed view.
},
};Either way the cycle is the one from App Structure: write, the store validates and notifies, subscribed data() re-runs, and the template patches.
Validation, for free
Try creating a bad record from the browser console, or a quick "add spell" form, and the schema pushes back:
store.createRecord('spell', { id: 's6', name: '', level: 12 });
// → throws PuzzleValidationError: name fails required(), level fails max(9)For form UX you'd rather warn than throw: Spell.validate(data) returns { valid, errors } without committing anything. The Data & Models reference covers that, plus relationships and syncing records with a server.
Where you've landed
In three short parts you've touched every subsystem from App Structure: a view that derives its screen from data(), a router giving each spell a URL, and a model making the data safe to change from anywhere. From here, go deeper wherever your app pulls you:
- Templates: the full grammar you've been sampling.
- Data & Models: relationships, server data, saving.
- Animations: enter/leave transitions for these same views.
- Static Builds: prerender the spellbook to real HTML.