Searching Puzzle

Type to search Puzzle.

Events & Binding

Declare handlers, bind form inputs, and pass callbacks between components.

Event handlers live in a single class field named events, an object whose values are arrow functions:

import { PuzzleView } from '@magic-spells/puzzle';

export default class TodoHome extends PuzzleView {
  created() {
    this.setData({ newTodoText: '', currentFilter: 'all' });
  }

  data(params, props) {
    const local = this.getData();
    return {
      todos: this.ctx.store.findMany('todo'),
      newTodoText: local.newTodoText,
      currentFilter: local.currentFilter,
    };
  }

  events = {
    addTodo: (event) => {
      event.preventDefault();
      const text = this.getData().newTodoText.trim();
      if (text) {
        this.ctx.store.createRecord('todo', { text });
        this.setData('newTodoText', '');
      }
    },
    setFilter: (filter) => {
      this.setData('currentFilter', filter);
    },
  };
}

Two rules follow from <script> being real JavaScript:

  • events is a class field (events = { ... };), not an object-literal member, and there are no commas between class members.
  • Every handler must be an arrow function.

Why arrow functions

A class-field initializer runs during construction, with this bound to the instance. Arrow functions have no this of their own, so they capture the surrounding this permanently. Every handler closes over the component for good, and the runtime can detach handlers and call them later without breaking the binding.

Method shorthand (addTodo(event) { ... }) compiles, but when the handler fires, this is the events object, so this.setData(...) throws. Development builds warn at the first mount when a non-arrow handler uses this. A shorthand handler that never uses it works without a warning.

Binding handlers in the template

Bind handlers with @ followed by the DOM event name. The value takes one of three forms:

FormTemplateWhat the handler receives
Bare identifier@click={ clearCompleted }Invoked as clearCompleted(event), the DOM event.
Handler call@click={ setFilter('all') }One call to one of the view's handlers. The arguments are ordinary template expressions, evaluated when the event fires, with event in scope. The handler gets exactly the arguments written.
Ternary@pointerdown:outside={ open ? close : null }Each branch is one of the two forms above or null. A null branch detaches the listener while the element stays mounted.
<form @submit={ addTodo(event) }>…</form>
<input type="checkbox" @change={ toggleTodo(todo) } />
<button @click={ setFilter('all') }>All</button>
<button @click={ clearCompleted }>Clear</button>
<div @pointerdown:outside={ menuOpen ? closeMenu : null }>…</div>

Notes on the call form:

  • Write event explicitly if the handler needs it: @submit={ addTodo(event) }. @click={ setFilter('all') } passes only 'all'; no event is appended.
  • The arguments use the same expression language as the rest of the template: data fields, loop variables, operators, and functions, as in @click={ move(item.id, items.length - 1) }. Inside {#for todo in todos}, @change={ toggleTodo(todo) } passes that iteration's record. There's no this: a value the handler needs comes from data(), or the handler reads it itself.
  • event is the DOM event, and a chain that starts from it reaches anything on the event: @input={ rename(event.target.value) }, @click={ pick(event.target.closest('li')) }. A loop variable named event wins over the DOM event.
  • The called name is always one of the view's own handlers, so a handler named like a library function (currency, say) calls the handler there and the function everywhere else, and Puzzle warns about the clash. Calls inside the arguments are ordinary functions.
  • The expression evaluates when the event fires, not at render time. Other shapes, such as @click={ a + b }, an inline arrow, or event.preventDefault() as the value, are compile errors. Anything that acts on the event belongs inside the handler, or in a modifier like :prevent.

A handler that doesn't capture render data is cached per instance, so re-renders don't rebind its listener and a component receiving it as a callback prop sees the same function every time. Inside a {#for}, a handler that captures only the loop item is cached on its row and reads the row's current item when it fires, so one record edit in a long list wakes one child instead of all of them.

Form binding

Form controls bind themselves. On a plain <input>, <textarea>, or <select>, a value= or checked= reads the source into the control and carries the user's edit back, with no handler:

<input type="text" placeholder="What needs doing?" value={ newTodoText } />
<input type="checkbox" checked={ todo.completed } />
<select value={ profile.plan }>
  <option value="free">Free</option>
  <option value="pro">Pro</option>
</select>

There's no directive and no bind: prefix: the shape of the expression is the whole signal. One rule decides the rest: bind the path you want written.

  • A bare key writes local state and re-runs data(), so anything derived from it (a filtered list, a disabled submit button) stays live as you type. Seed the key in created() and read it back in data() so it survives store-driven re-runs.
  • A member path on a store record writes through update(), so schema validation runs and every subscribed view re-renders. A rejected write reports to the app's onError hook with phase: 'bind' and leaves the typed text on screen. While the root is missing (profile is null), the binding is inert.
  • Don't bind a local key that data() derives from a record. The next commit reverts it, and development warns once per key. Bind the record path instead.

When a control binds

Every condition must hold; anything else compiles as a one-way display binding, silently:

ConditionBindsStays one-way
Elementa plain <input>, <textarea>, or <select>any component tag, where value is an ordinary prop
Expressiona bare identifier or one-member path: draft, todo.completeddraft || '', draft ?? '', a.b.c, items[i], ternaries, function calls, a bare loop variable
Handlersno @input or @change on the elementan author @input or @change, which owns the write
Attributesno static readonly or disabledeither one present
typeabsent, or a static type from the table belowa dynamic type={ … }; file, radio, hidden, and button types; <select multiple>; value= on a checkbox
ControlCommits onWrites
text-like inputs (no type, text, search, email, password, url, tel, color) and <textarea>inputa string
type="range"inputa number
type="number"changea number; an emptied field writes null, never 0
type="checkbox" with checked=changea boolean
date and time types, single <select>changea string

Numbers commit on change because coercing mid-typing would rewrite the field under the caret. A keystroke inside an IME composition never writes; the composed text lands when the composition ends.

Constrained fields: bind a draft, commit on submit

A bound record path validates on every keystroke, which is wrong for a field the user has to type through: a required() field could never be emptied, and a min(3) rule rejects the first two characters. Bind a local draft instead, check it with the non-throwing validate(), and commit once:

<form @submit={ save(event) }>
  <textarea value={ textDraft }></textarea>
  {#if textError}<p class="field-error">{ textError }</p>{/if}
  <button type="submit">Save</button>
</form>
import Comment from '@/models/comment.js'; // at the top of the <script> block

events = {
  save: (event) => {
    event.preventDefault();
    const { textDraft } = this.getData();
    // validate() reports without throwing
    const { valid, errors } = Comment.validate({ text: textDraft }, { fields: ['text'] });
    if (!valid) {
      this.setData('textError', errors[0].message);
      return;
    }
    this.props.comment.update({ text: textDraft });
    this.setData('textError', null);
  },
};

Opting out

Three escapes, all ordinary syntax: write your own @input or @change (it suppresses the synthesized write completely), use a non-path expression such as value={ name ?? '' }, or add a static readonly. Handlers on other events, like @keydown:enter or @blur, coexist with the binding rather than replacing it. So a field wired as value={ name } with only an Enter handler is not an edit buffer you can abandon: every keystroke has already landed in name. Use the non-path form when Escape needs something to revert to.

Updating state from handlers

Handlers have two levers, and they behave differently.

Local state: setData

Use setData for local UI state: toggles, open panels, the current filter:

events = {
  toggleMenu: () => {
    this.setData('menuOpen', !this.getData().menuOpen);
  },
};

setData updates state and re-renders, but does not re-run data(). That keeps small updates cheap. If a template value is derived inside data() from local state, call this.refresh() after setData to recompute it (see Components). A bound bare key does that for you.

Store mutations: reactive by design

Creating, updating, or destroying a record re-runs data() on every component subscribed to those records, meaning any component that queried them in data():

events = {
  markAllComplete: () => {
    const active = this.ctx.store.findMany('todo').filter((t) => !t.completed);
    active.forEach((todo) => todo.update({ completed: true }));
    // Every component whose data() queried 'todo' re-runs and re-renders.
  },
};

Don't copy store results into local state and mutate the copy. Mutate the records through update() and let the store notify subscribers; assigning a field directly (todo.title = 'x') is never observed.

ChangeMechanismRe-runs data()?
Local UI statethis.setData(...)No: direct state update and re-render
Shared recordsstore.createRecord / record.update() / record.destroy()Yes, on every subscribed component

Event modifiers

A binding can carry :modifier suffixes that adjust dispatch declaratively: @event:modifier[:modifier…]={ handler }. They stack.

ModifierEffectApplies to
preventevent.preventDefault()any event
stopevent.stopPropagation()any event
oncehandler fires once ever for this bindingany event
outsidehandler runs only when the event lands outside the elementany event
key filterhandler runs only when the key matcheskeydown / keyup / keypress

Key filters map to event.key: enter, escape, tab, space, up, down, left, right, backspace, delete.

<input @keydown:enter={ addTodo(event) } @keydown:escape:prevent={ cancelEdit } />
<a href="/home" @click:prevent:stop={ navigate('/home') }>Home</a>
<button @click:once={ claimReward }>Claim (once)</button>

When modifiers stack, dispatch runs them in a fixed order regardless of how you write them: outside-gate, key-gate, once-spend, preventDefault, stopPropagation, handler. The gates run first, so an inside event or a non-matching key bails before preventDefault and without spending once.

A handler that should intercept a key only sometimes (Backspace only when the caret is at offset 0, say) shouldn't combine a key filter with :prevent, which prevents every matching press before the handler can decide. Use the filter alone, or a plain @keydown handler, and call event.preventDefault() after the handler's guard.

An unknown modifier, a key filter on a non-keyboard event, a duplicate modifier, more than one key filter, or any modifier on a component callback prop is a compile error.

Outside dismiss

:outside is declarative dismissal for popovers, menus, and dropdowns. The framework attaches the listener to document in the capture phase and removes it when the element unmounts, so you never hand-roll a document listener for this:

<button @click={ toggle }>Options</button>
{#if open}
  <div class="menu" @pointerdown:outside={ close } @keydown:escape={ close }>
    …
  </div>
{/if}

Put the binding on the panel root inside {#if open} so the listener lives exactly as long as the panel, or use the null toggle on an always-mounted element. It works with any event: @focusin:outside fires when focus leaves a widget. Content inside a <Portal> counts as inside its owner. Events inside an <iframe> never reach the page, and on touch pointerdown fires at scroll start, so prefer @click:outside where scrolling matters.

Component events: callbacks down, calls up

There's no $emit, no bubbling, and no event bus. Child-to-parent communication uses callback props: a parent passes a function down, and the child calls it.

When a parent writes <Button @press={ savePost }>Save</Button>, the parent's handler is not attached to any DOM node inside the child. It's handed to the child as a prop (this.props.press), and the child's own DOM handler invokes it:

<!-- components/Button.pzl -->
<puzzle-view>
  <button class="btn" disabled={ disabled } @click={ handleClick }>
    <Children/>
  </button>
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';

export default class Button extends PuzzleView {
  data(params, props) {
    return { disabled: props.disabled || false };
  }

  events = {
    handleClick: (event) => {
      if (this.getData().disabled) return;    // child gates the event
      const { press } = this.props;
      if (typeof press === 'function') press(event);   // parent's function does the work
    },
  };
}
</script>
<!-- parent -->
<Button @press={ savePost } variant="primary">Save</Button>

The pattern: event handling lives in the child; behavior lives in the parent. The child gates and shapes (a disabled button doesn't fire; a modal's confirm passes form values instead of a raw event), and the parent's function does the work with the parent's state. Guard the prop before calling it, since a caller may not pass one.

If the child has nothing to add, its handler just forwards: handleClick: (event) => this.props.press?.(event). The template can't call press directly, because a call in an @event value always names one of the view's own handlers. If a callback prop is wired into a long-lived external system, read it when it fires ((e) => this.props.change?.(e)) rather than capturing it once.

The parent-owned-mutation pattern

A child reports intent; the parent owns the change. Passing the loop variable through the callback is common:

<!-- parent template -->
{#for comment in comments}
  <CommentItem comment={ comment } @remove={ removeComment(comment) } />
{/for}
// parent
events = {
  removeComment: (comment) => {
    comment.destroy();   // the parent decides what "remove" means
  },
};
// CommentItem.pzl: only reports intent
events = {
  handleRemove: () => {
    const { remove } = this.props;
    if (typeof remove === 'function') remove();
  },
};

Imperative handles: the @ready idiom

ref isn't allowed on component tags. When a child owns something imperative the parent needs (a carousel's .next(), a video element, a third-party widget), the child delivers the handle up through a callback prop, once, when it exists:

<!-- parent template -->
<TarotCarousel options={ carouselOptions } @ready={ carouselReady }>…</TarotCarousel>
// parent
events = {
  carouselReady: (carousel) => {
    this._carousel = carousel;   // instance field, NOT setData (a DOM handle isn't view data)
  },
  nextSlide: () => {
    this._carousel?.next();       // always guard: the handle arrives async
  },
};

Conventions: name the prop @ready, deliver the handle once from the child's mounted() (or later if the library boots asynchronously), store it on an instance field (not setData), and guard every use with ?.. If the child is destroyed and remounted, a new handle arrives through a new @ready call, so don't keep driving the old one.

For a plain element in your own template, use the first-class ref="name" attribute instead (see Templates).

Common mistakes

  1. Method shorthand in events: it compiles, but this is the events object at event time. Development warns when the handler uses it. Use an arrow function.
  2. Curried handlers: (todo) => () => { … } is not the pattern. The call form passes arguments directly, so write a plain arrow that takes them: toggleTodo: (todo) => { todo.toggle(); }.
  3. An input handler you don't need: value={ draft } already writes draft. Adding @input turns the synthesized write off, so you own it from then on.
  4. Mutating instead of calling setData or update(): assigning to a variable, to a property of the object getData() returned, or to a record field changes nothing on screen.
  5. Commas between class members: events is a class field, so separate it from methods with whitespace. Commas belong only inside the object literal, between handlers.

Next