observeMany
Overview
Section titled “Overview”The observeMany
function allows you to create observers that react to changes in multiple ref objects simultaneously. This is useful for handling side effects or updating UI elements based on changes in multiple reactive data sources.
Creating Observers for Multiple Refs
Section titled “Creating Observers for Multiple Refs”To create an observer for multiple ref objects, you can use the observeMany
function, passing in an array of ref objects and a callback function.
import { observeMany, ref } from 'regor'
const ref1 = ref('Hello')const ref2 = ref('World')
// Create an observer for multiple refsconst stopObserving = observeMany([ref1, ref2], (newValues) => { console.log('Values changed:', newValues)})
Parameters
Section titled “Parameters”sources
: An array of ref objects you want to observe for changes.observer
: A callback function that will be triggered whenever any of the ref values change. The callback receives an array of the current values of all observed refs.init
(optional): Iftrue
, the observer will be immediately invoked with the current values of the refs when it’s created.
Return Value
Section titled “Return Value”- The
observeMany
function returns astopObserving
function that allows you to stop the observer when it’s no longer needed. CallingstopObserving
will unsubscribe the observer from all the observed ref objects.
Example
Section titled “Example”import { observeMany, ref } from 'regor'
const ref1 = ref('Hello')const ref2 = ref('World')
// Create an observer for multiple refs with init set to trueconst stopObserving = observeMany( [ref1, ref2], (newValues) => { console.log('Values changed:', newValues) }, true,)
// Later, when the observer is no longer needed, stop itstopObserving()