Watchers and Listeners
This example shows the difference between watch and addStateListener() when a component needs both internal reactions and external integration hooks.
Live Demo
Section titled “Live Demo”Component
Section titled “Component”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}` ); }, },});External subscription
Section titled “External subscription”const instance = Counter.mount("[data-counter]");
const cleanup = instance.addStateListener("count", ({ newValue, oldValue }) => { console.log(`External listener: ${oldValue} -> ${newValue}`);});How to think about it
Section titled “How to think about it”watchlives inside the component definitionaddStateListener()is attached to a mounted instance from the outsidewatchis for component-owned side effectsaddStateListener()is for integrations and orchestration
Rule of thumb
Section titled “Rule of thumb”- use
renderfor DOM output - use
computedfor derived values - use
watchfor internal side effects - use
addStateListener()for external subscriptions