Skip to content

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);
});

The listener receives an event object with:

  • property: the state property name that changed, such as "count"
  • newValue: the incoming value from the update
  • oldValue: the outgoing value from the update
  • target: the mounted component instance that emitted the change
instance.addStateListener(
'count',
({ property, newValue, oldValue, target }) => {
console.log(property, newValue, oldValue, target);
}
);

addStateListener() returns a cleanup function.

const cleanup = instance.addStateListener('count', (event) => {
console.log(event.newValue);
});
cleanup();

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

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.