Skip to content

Watchers and Listeners

This example shows the difference between watch and addStateListener() when a component needs both internal reactions and external integration hooks.

Open this demo in a new tab

import { defineComponent } from "ornata";
export const Counter = defineComponent({
name: "Counter",
state: {
count: { default: 0, type: Number },
},
methods: {
increment() {
this.state.count += 1;
},
},
watch: {
count({ isInitial, newValue, oldValue }) {
if (isInitial) return;
console.log(
`Internal watcher: ${oldValue} -> ${newValue}`
);
},
},
});
const instance = Counter.mount("[data-counter]");
const cleanup = instance.addStateListener("count", ({ newValue, oldValue }) => {
console.log(`External listener: ${oldValue} -> ${newValue}`);
});
  • watch lives inside the component definition
  • addStateListener() is attached to a mounted instance from the outside
  • watch is for component-owned side effects
  • addStateListener() is for integrations and orchestration
  • use render for DOM output
  • use computed for derived values
  • use watch for internal side effects
  • use addStateListener() for external subscriptions