signalizejs/signal
Reactive primitive that can be watched, used to create stores, or bound to element properties and attributes.
Installation
const {
signal,
Signal
} = await signalize.resolve('signal');
API
signal
Signals in a nutshell:
- A
signalin Signalize is basically a “variable” that you can watch for changes or when its value is accessed. - Every signal you create while using Signalize is an instance of the
Signalclass. - The method
signalcreates a new instance of theSignalclass with the value you pass in during initialization.
Let’s start with how a signal can be used:
// 1. Creating a signal
const number = signal(0);
// 2. Setting a new value: from 0 => 1;
// You need to pass a value
number(1)
// 3. Getting signal value
// You just call the method
const actualNumber = number(); // => 1
// 4. We may want to watch the signal
// See docs below for more info
// 4.1 Triggered after every set
const unwatch = number.watch(({ newValue, oldValue }) => {});
// 4.2 Triggered immediately
number.watch(({ newValue, oldValue }) => {}, { immediate: true });
// 4.3 Triggered before the value is set
number.watch(({ newValue, oldValue }) => {
return {
// If false, the new value will not be set
settable: true,
// We can also modifie the value within the watcher
value: newValue
}
}, { execution: 'beforeSet'});
// 4.4 - And if we want to track the signal value usage
// we can watch it on every get call
number.watch(({ newValue, oldValue }) => {}, { execution: 'onGet' });
Signals can be watched for the following events. See the example below:
- on every get - To track places where the signal is used.
- before it is set -Useful to check the new value and possibly modify the value or block the setter.
- after it is set - Trigger some callback like recalculating variables that depend on the signal.
Signals are often used with the bind method.
Below is an example with two number inputs:
- Signals are connected to elements using the bind method.
- Signals are watched using
.watch()method. - When any signal changes, it updates the output under the input elements.
numberBcannot be lower thannumberA. It’s always +1 higher thannumberA.
__CODE__