sref
Overview
Section titled “Overview”The sref
function converts a given value into an sref (short for “simple ref”) object and returns the sref. An sref allows you to both retrieve and update its value.
The nested properties of an sref are not converted to refs.
Getting the SRef Value
Section titled “Getting the SRef Value”You can access the value of the sref object using two methods:
srefObj.value
: Accesses the value directly.srefObj()
: Invokes the sref object to retrieve its value.
Setting the SRef Value
Section titled “Setting the SRef Value”To update the value of an sref object, you have two options:
srefObj.value = newValue
: Sets the value directly.srefObj(newValue)
: Invokes the sref object with the new value to update it.
Parameters
Section titled “Parameters”-
value
(optional): Any value that you want to convert into an sref object. The function supports several input types:- Basic types such as numbers, strings, booleans, Date etc.
- sref objects.
- objects
- Array, Map, Set.
null
orundefined
.
Return Value
Section titled “Return Value”The sref
function returns an sref object representing the input value. The specific type of the returned sref object depends on the input value’s type.
-
sref
modifies prototype of arrays, maps, and sets to make them reactive. -
Observers can be attached to the sref object to be notified of changes to its value.
-
The function also supports batch collecting changes and pausing/resuming auto-triggering of observers.
-
Every
ref
is ansref
, but not everysref
is aref
.
Example
Section titled “Example”import { sref } from 'regor'
const initialValue = { name: 'John', age: 30, hobbies: ['reading', 'swimming'],}
const mySRef = sref(initialValue)
// Accessing the sref value using function callconsole.log(mySRef()) // Outputs the initial value
// Accessing the sref value using value getterconsole.log(mySRef.value) // Outputs the initial value
// Updating the sref valuemySRef().name = 'Alice' // Directly modifying the sref valueconsole.log(mySRef().name) // Outputs 'Alice'
mySRef({ name: 'Alice', age: 35, hobbies: ['reading', 'swimming'],}) // Invoking the sref with a new valueconsole.log(mySRef().age) // Outputs 35