- Docs
- Observe a field with observe()
Observe a field with observe()
Registers a callback that fires immediately with the current value and on every subsequent change. Returns an unsubscribe function.
Registers a callback that fires immediately with the current value and on every subsequent change. Returns an unsubscribe function.
Signature
observe(field: string, callback: FormFieldWatcher): () => void
observe(fields: string[], callback: FormFieldsWatcher): () => void
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
field |
string |
yes | The name attribute of the field to observe. |
callback |
FormFieldWatcher |
yes | Invoked with (value, field, form, state). Fires immediately with the current value, then on every change. field is the observed DOM element(s) (same shape as getField returns). |
Pass an array of names to observe several fields with one callback. It receives (values, changed, form, state), typed as FormFieldsWatcher: values has one entry per field, and changed is the field that triggered the call, or null on registration and after reset. See watch for the details.
Returns
A function. Calling it removes the observer for this field.
Behaviour
- On registration, the callback is invoked once synchronously with the current value, the bound form, and a state snapshot.
- Subsequent user
inputevents and programmaticsetValuecalls invoke the callback again. DOM mutations alone do not fire field watchers, with one exception: adding or removing<option>elements in a way that changes a select’s value fires that field’s watchers. - A field can have multiple observers.
- The unsubscribe function is idempotent — calling it more than once is safe.
Examples
Observe several fields
import { form } from '@samline/forms'
const order = form('order-form')
const stop = order.observe(['quantity', 'price'], ({ quantity, price }) => {
document.querySelector('#total')!.textContent = String(Number(quantity) * Number(price))
})
stop()
Observe and unsubscribe later
import { form } from '@samline/forms'
const profile = form('profile-form')
const stop = profile.observe('email', value => {
console.log('email is now:', value)
})
// Later, when the form is unmounted:
stop()
Sync a derived model
import { form } from '@samline/forms'
const checkout = form('checkout-form')
const unsubscribe = checkout.observe('shippingMethod', (value, field, _form, state) => {
const total = computeTotal(state.values)
document.querySelector('#total')!.textContent = String(total)
if (field && 'name' in field) {
console.log(`updated ${field.name} ->`, value)
}
})
window.addEventListener('beforeunload', unsubscribe)
Share a handler across fields
import { form } from '@samline/forms'
const signup = form('signup-form')
const track = (value: unknown, field: HTMLInputElement | HTMLInputElement[] | null) => {
const name = field && 'name' in field ? field.name : null
analytics.track('signup_field_changed', { field: name, value })
}
const offEmail = signup.observe('email', track)
const offPassword = signup.observe('password', track)
// Later, on teardown:
offEmail()
offPassword()
Manipulate the watched element directly
import { form } from '@samline/forms'
const profile = form('profile-form')
const stop = profile.observe('avatar', (_value, field) => {
if (field instanceof HTMLInputElement) {
field.setAttribute('data-touched', 'true')
}
})
Multiple observers on the same field
import { form } from '@samline/forms'
const signup = form('signup-form')
const offA = signup.observe('password', value => updateStrength(value))
const offB = signup.observe('password', value => updateCapsLockWarning(value))
// Remove only the strength meter.
offA()
Edge cases
- The initial fire happens synchronously inside
observe. If you do not want this, usewatchinstead. - Observers persist across calls to
resetandsetValue— they are not affected by state changes. - The unsubscribe function only removes this specific callback. Other observers on the same field continue to fire.
Related
watch— chainable, no unsubscribe.unwatch— bulk removal of watchers.subscribe— global state observer.format— when a field is formatted,observe('<field>', cb)fires with the raw value andobserve('<field>_displayed', cb)fires with the formatted value. Both fire on the same keystroke. See the mirror convention.