State Listeners
addStateListener() is the public subscription API on a mounted Ornata component instance. It lets code outside the component observe changes to a specific public state property.
const instance = Counter.mount('[data-counter]');
const cleanup = instance.addStateListener('count', (event) => { console.log(event.newValue);});What the listener receives
Section titled “What the listener receives”The listener receives an event object with:
property: the state property name that changed, such as"count"newValue: the incoming value from the updateoldValue: the outgoing value from the updatetarget: the mounted component instance that emitted the change
instance.addStateListener( 'count', ({ property, newValue, oldValue, target }) => { console.log(property, newValue, oldValue, target); });Cleanup
Section titled “Cleanup”addStateListener() returns a cleanup function.
const cleanup = instance.addStateListener('count', (event) => { console.log(event.newValue);});
cleanup();When to use state listeners
Section titled “When to use state listeners”Use addStateListener() when:
- external code needs to observe a component
- another system needs to react to state changes
- you are coordinating behavior between mounted instances
- you want subscriptions without putting more logic inside the component itself
A good mental model
Section titled “A good mental model”State listeners are for external observers. They are a clean way to integrate a mounted Ornata component into wider page behavior without reaching into its internals.