Dependent Fields
A dependent field is a purely output field whose value changes whenever at least one field it depends on changes -- see when the resolver runs.
Default values
A dependent field must declare a default value: .default(value) for a static default, or
.default(resolver) for one computed from the creation context when the field is created. The
default is used until the field's resolver runs (see
when the resolver runs). Both resolvers receive the operation context.
When the resolver runs
- On create, a dependent resolves when at least one of its parents:
- is a required or virtual field that was provided and accepted;
- is a lax field that was provided and accepted with a value other than its static default, or whose default comes from a resolver (a function), provided or not;
- is a dependent field that resolved to a value other than its default, or whose default comes from a resolver.
- On update, a dependent resolves when at least one of its parents:
- is a virtual field that was provided and accepted (always, since it has no previous value);
- is a required or lax field that was provided and accepted with a value other than its previous one;
- is a dependent field that resolved to a value other than its previous one.
A dependent that resolves to the value it already had is not a change, so the dependents below it don't resolve. Dependents resolve in dependency order, each one at most once per operation, after all its parents: a dependent with several parents never resolves twice.
Try it
An order whose dependents form a graph: subtotal depends on price and quantity, discount
on the virtual coupon, total on both, and shipping on total. Choose which inputs to
provide, then create or update the record to see which resolvers run, in order. It runs ivo in
your browser.
A parent left at its static default
A dependent resolving to its previous value
Several parents changing at once
Readonly
readonly() is only available when the default is a static value. It locks the field once its
value has diverged from the default: its parents changing no longer re-resolve it.
With a resolver default, readonly() is not offered; the resolver itself controls when the field
is recomputed.
Hooks
Dependent fields support onDelete and onSuccess listeners.
API summary
| Method | Description |
|---|---|
dependent(name, dependsOn) | Create a dependent field. dependsOn can be a single field or an array. |
default(value) | Static default used when no dependency is triggered. |
default(resolver).resolve(r) | Computed default; resolver runs when a dependency changes. |
readonly() | Locks after divergence; only with a static default. |
onDelete(handler) | Listener invoked by model.delete. |
onSuccess(handler) | Listener invoked after a successful create/update. |