observe
Overview
Section titled “Overview”The observe
function allows you to create observers that react to changes in ref objects, providing a callback that triggers when the ref’s value changes. This is useful for handling side effects or updating UI elements based on reactive data.
Creating Observers
Section titled “Creating Observers”To create an observer, you can use the observe
function, passing in a ref object and a callback function.
import { observe, ref } from 'regor'
const myRef = ref('Hello, Regor!')
// Create an observerconst stopObserving = observe(myRef, (newValue) => { console.log('Value changed:', newValue)})
Parameters
Section titled “Parameters”source
: The ref object you want to observe for changes.observer
: A callback function that will be triggered whenever the ref’s value changes.init
(optional): Iftrue
, the observer will be immediately invoked with the current value of the ref when it’s created.
Return Value
Section titled “Return Value”- The
observe
function returns astopObserving
function that allows you to stop the observer when it’s no longer needed. CallingstopObserving
will unsubscribe the observer from the ref object.
Example
Section titled “Example”import { observe, ref } from 'regor'
const myRef = ref('Hello, Regor!')
// Create an observer with init set to trueconst stopObserving = observe( myRef, (newValue) => { console.log('Value changed:', newValue) }, true,)
// Later, when the observer is no longer needed, stop itstopObserving()