import{_ as i,o as a,c as t,ae as n}from"./chunks/framework.C8AWLET_.js";const o=JSON.parse('{"title":"⚡ Reactivity Control: $.watch( )","description":"","frontmatter":{},"headers":[],"relativePath":"api/watch.md","filePath":"api/watch.md"}'),e={name:"api/watch.md"};function h(l,s,p,k,r,d){return a(),t("div",null,[...s[0]||(s[0]=[n(`
$.watch( ) The $.watch function is the reactive engine of SigPro. It allows you to execute code automatically when signals change. In V2, $.watch is polymorphic: it can track dependencies automatically or follow an explicit list.
// Automatic Mode (Magic Tracking)
$.watch(callback: Function): StopFunction
// Explicit Mode (Isolated Dependencies)
$.watch(deps: Signal[], callback: Function): StopFunction| Parameter | Type | Required | Description |
|---|---|---|---|
target / deps | Function | Array | Yes |
callback | Function | Only in Explicit | The code that will run when the deps change. |
Returns: A StopFunction that, when called, destroys the watcher and releases memory.
Any signal you "touch" inside the callback becomes a dependency. SigPro tracks them behind the scenes.
const count = $(0);
$.watch(() => {
// Re-runs every time 'count' changes
console.log(\`Count is: \${count()}\`);
});This mode isolates execution. The callback only triggers when the signals in the array change. Any other signal accessed inside the callback will NOT trigger a re-run. This is the "gold standard" for Routers and heavy components.
const sPath = $("/home");
const user = $("Admin");
$.watch([sPath], () => {
// Only triggers when 'sPath' changes.
// Changes to 'user' will NOT trigger this, preventing accidental re-renders.
console.log(\`Navigating to \${sPath()} as \${user()}\`);
});If your logic creates timers, event listeners, or other reactive effects, SigPro tracks them as "children" of the current watch. When the watcher re-runs or stops, it kills everything inside automatically.
$.watch(() => {
const timer = setInterval(() => console.log("Tick"), 1000);
// Register a manual cleanup if needed
// Or simply rely on SigPro to kill nested $.watch() calls
return () => clearInterval(timer);
});Call the returned function to manually kill the watcher. This is essential for manual DOM injections (like Toasts) or long-lived background processes.
const stop = $.watch(() => console.log(count()));
// Later...
stop(); // The link between the signal and this code is physically severed.SigPro batches updates. If you update multiple signals in the same execution block, the watcher will only fire once at the end of the task.
const a = $(0);
const b = $(0);
$.watch(() => console.log(a(), b()));
// This triggers only ONE re-run.
a(1);
b(2);