- Docs
- React to a field with watch()
React to a field with watch()
Registers a callback that fires immediately and every time a field changes. Chainable alias of observe() for fluent setup without an unsubscribe.
Registers a callback that fires every time a field changes. Chainable alias of observe; use it when you want fluent setup without holding the unsubscribe function.
Signature
watch(field: string, callback: FormFieldWatcher): FormController
watch(fields: string[], callback: FormFieldsWatcher): FormController
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
field |
string |
yes | The name attribute of the field to watch. |
callback |
FormFieldWatcher |
yes | Invoked with (value, field, form, state) on every change. field is the observed DOM element(s) (same shape as getField returns), handy for manipulating the actual <input> / <select> / <textarea> without re-querying it. |
Pass an array of names to watch several fields with one callback. The callback then receives (values, changed, form, state) instead, typed as FormFieldsWatcher:
| Argument | Description |
|---|---|
values |
One entry per watched field, read with getValue. |
changed |
The name of the field that triggered the call, or null on registration and after reset. |
form |
The bound HTMLFormElement. |
state |
A snapshot of the whole controller state. |
Returns
The same FormController — chainable.
Behaviour
- The callback fires immediately on registration and after every change, matching
observe(); only the return type differs. - A field can have multiple watchers.
- With an array, the callback fires once on registration (
changed: null), once per change of any listed field, and once afterreset(). Changes to fields that are not listed do not call it. Duplicate names are ignored and an empty array registers nothing. - Watchers persist for the lifetime of the controller. Use
unwatchto remove them, orobserveif you need explicit unsubscribe semantics. - The callback fires after the controller has processed the change — manual errors are cleared (when applicable), validation has run for fields with rules, visual state has been re-synced, and subscribers have been notified.
Examples
Show a live preview
import { form } from '@samline/forms'
const profile = form('profile-form')
profile.watch('bio', value => {
const preview = document.querySelector('#bio-preview')
if (preview && typeof value === 'string') preview.textContent = value
})
Reactive password strength
import { form } from '@samline/forms'
const signup = form('signup-form')
signup.watch('password', value => {
const meter = document.querySelector('#password-strength')
if (meter && typeof value === 'string') {
meter.textContent = scorePassword(value)
}
})
Share a single handler across fields
import { form } from '@samline/forms'
const search = form('search-form')
const logField = (value: unknown, field: HTMLInputElement | HTMLInputElement[] | null) => {
if (field && 'name' in field) {
console.log(`${field.name} =`, value)
}
}
search.watch('q', logField).watch('category', logField)
Watch several fields with one callback
import { form } from '@samline/forms'
const order = form('order-form')
order.watch(['quantity', 'price'], ({ quantity, price }, changed) => {
const total = Number(quantity) * Number(price)
document.querySelector('#total')!.textContent = total.toFixed(2)
if (changed) console.log(`${changed} changed`)
})
Interact with the field element directly
import { form } from '@samline/forms'
const checkout = form('checkout-form')
checkout.watch('country', (_value, field, _form, _state) => {
if (field instanceof HTMLSelectElement) {
// Toggle a CSS class on the actual <select> without re-querying it.
field.classList.toggle('has-zip', field.value !== 'US')
}
})
Chain with other setup
form('search-form')
.watch('q', value => console.log('q =', value))
.watch('category', value => console.log('category =', value))
.onSubmit((_form, data) => console.log('submit', data))
Edge cases
- The callback receives the value, not the event object. Use
getFieldif you need the underlying DOM element. watchfires immediately, just likeobserve; it differs only by returning the controller instead of an unsubscribe function.- A field name that does not match any DOM field receives one initial call with
undefinedandnull. It runs again only if aninputevent later comes from a field with that name. - Watchers are not invoked from
setValuedirectly.setValuewrites the value and dispatches oneinputevent, which goes through the same delegated listener path as user input.
Related
observe— same immediate callback, but returns an unsubscribe function.unwatch— remove watched callbacks.subscribe— react to the whole form state.format— when a field is formatted,watch('<field>', cb)fires with the raw value andwatch('<field>_displayed', cb)fires with the formatted value. Both fire on the same keystroke. See the mirror convention.