Model listeners¶
A concept can react to edits made to its own nodes. Declare a listeners() method on the concept class and return
handlers keyed by event. The editor runs them after each committed edit, so a concept can keep itself consistent
(fill a default, normalise a name, add a required child) without every write path knowing about it.
class Release extends Concept(IStatement) {
changes = ChildSlot({ type: IStatement, cardinality: "0..n" });
listeners() {
return {
// A freshly inserted blank change adopts the category of the one before it.
onChildAdded(ev) {
const added = ev.child;
if (added.head !== "change" || added.children[0] !== "Added" || added.children[1]) return;
const before = ev.node.children.slice(3, ev.index).reverse().find((c) => c.head === "change");
if (before) added.children[0] = before.children[0];
},
};
}
}
Events¶
| Handler | Runs when | Useful fields |
|---|---|---|
onChildAdded(ev, ctx) |
a child node appeared in this node | ev.child, ev.index, ev.slot |
onChildRemoved(ev, ctx) |
a child node left this node | ev.child (detached), ev.index, ev.slot |
onProperty(ev, ctx) |
a primitive slot changed | ev.index, ev.slot, ev.oldValue, ev.newValue |
onReference(ev, ctx) |
the same, on an IReference concept |
same |
ev.node is the node that owns the slot, and it is always of the concept declaring the handler (or a subconcept).
ctx carries lang, root, editor and pass.
Rules¶
- Mutate freely, but be idempotent. Your writes join the same undo step as the user's edit. They are diffed again (up to 8 passes), so a handler that always changes something it listens to is stopped and an error is shown. Check the state before writing, as in the example.
- Do not use
this. Handlers are collected once from a probe instance, likecomputed(). - Keep them cheap. A handler over 50 ms logs a warning (once). A listener on a base concept runs for all its subconcepts.
- Remote edits do not trigger them. In a Live Model Session the peer who typed ran the listeners, and their writes arrive with the edit. Handlers must still be idempotent because two peers can edit at once.
- Code only. Listeners are not saved in
.lang.js; they come from the concept class.
How events are derived, the guardrails and the collab decision are described in the developer architecture page.