Using signals to manage reactivity
How a program responds to variable data or user interactions is one of the fundamental problems of programming. If we desire to solve the issue in a declarative manner, signals may be a viable approach.
// use NPM or for example https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js
import { S, signal } from "deka-dom-el/signals";
S===signal
/** @type {ddeSignal} */
/** @type {ddeAction} */
/** @type {ddeActions} */
-
# Introducing signals
Using signals, we split program logic into the three parts. Firstly (α), we create a variable (constant) representing reactive value. Somewhere later, we can register (β) a logic reacting to the signal value changes. Similarly, in a remaining part (γ), we can update the signal value.
import { S } from "./esm-with-signals.js";
+
# Introducing signals
Let’s re-introduce 3PS principle.
Using signals, we split program logic into the three parts. Firstly (α), we create a variable (constant) representing reactive value. Somewhere later, we can register (β) a logic reacting to the signal value changes. Similarly, in a remaining part (γ), we can update the signal value.
import { S } from "./esm-with-signals.js";
// α — `signal` represents a reactive value
const signal= S(0);
// β — just reacts on signal changes
@@ -16,7 +16,7 @@ update();
const interval= 5*1000;
setTimeout(clearInterval, 10*interval,
setInterval(update, interval));
-
All this is just an example of Event-driven programming and Publish–subscribe pattern (compare for example with fpubsub library). All three parts can be in some manner independent and still connected to the same reactive entity.
Signals are implemented in the library as functions. To see current value of signal, just call it without any arguments console.log(signal())
. To update the signal value, pass any argument signal('a new value')
. For listenning the signal value changes, use S.on(signal, console.log)
.
Similarly to the on
function to register DOM events listener. You can use AbortController
/AbortSignal
to off/stop listenning. In example, you also found the way for representing “live” piece of code computation pattern (derived signal):
import { S } from "./esm-with-signals.js";
+
All this is just an example of Event-driven programming and Publish–subscribe pattern (compare for example with fpubsub library). All three parts can be in some manner independent and still connected to the same reactive entity.
Signals are implemented in the library as functions. To see current value of signal, just call it without any arguments console.log(signal())
. To update the signal value, pass any argument signal('a new value')
. For listenning the signal value changes, use S.on(signal, console.log)
.
Similarly to the on
function to register DOM events listener. You can use AbortController
/AbortSignal
to off/stop listenning. In example, you also found the way for representing “live” piece of code computation pattern (derived signal):
import { S } from "./esm-with-signals.js";
const signal= S(0);
// computation pattern
const double= S(()=> 2*signal());
@@ -32,7 +32,7 @@ ac.signal.addEventListener("abort",
()=> setTimeout(()=> clearInterval(id), 2*interval));
setTimeout(()=> ac.abort(), 3*interval)
-
# Signals and actions
S(/* primitive */)
allows you to declare simple reactive variables, typically around immutable primitive types. However, it may also be necessary to use reactive arrays, objects, or other complex reactive structures.
import { S } from "./esm-with-signals.js";
+
# Signals and actions
S(/* primitive */)
allows you to declare simple reactive variables, typically, around immutable primitive types. However, it may also be necessary to use reactive arrays, objects, or other complex reactive structures.
import { S } from "./esm-with-signals.js";
const signal= S(0, {
increaseOnlyOdd(add){
console.info(add);
@@ -50,7 +50,7 @@ setTimeout(
10*interval,
setInterval(oninterval, interval)
);
-
…but typical user-case is object/array (maps, sets and other mutable objects):
import { S } from "./esm-with-signals.js";
+
…but typical user-case is object/array (maps, sets and other mutable objects):
import { S } from "./esm-with-signals.js";
const todos= S([], {
push(item){
this.value.push(S(item));
@@ -106,7 +106,7 @@ function radio({ textContent, checked= false }){
" ",textContent
)
}
-
In some way, you can compare it with useReducer hook from React. So, the S(<data>, <actions>)
pattern creates a store “machine”. We can then invoke (dispatch) registered action by calling S.action(<signal>, <name>, ...<args>)
after the action call the signal calls all its listeners. This can be stopped by calling this.stopPropagation()
in the method representing the given action. As it can be seen in examples, the “store” value is available also in the function for given action (this.value
).
# Reactive DOM attributes and elements
There are on basic level two distinc situation to mirror dynamic value into the DOM/UI
- to change some attribute(s) of existing element(s)
- to generate elements itself dynamically – this covers conditions and loops
import { S } from "./esm-with-signals.js";
+
In some way, you can compare it with useReducer hook from React. So, the S(<data>, <actions>)
pattern creates a store “machine”. We can then invoke (dispatch) registered action by calling S.action(<signal>, <name>, ...<args>)
after the action call the signal calls all its listeners. This can be stopped by calling this.stopPropagation()
in the method representing the given action. As it can be seen in examples, the “store” value is available also in the function for given action (this.value
).
# Reactive DOM attributes and elements
There are on basic level two distinc situation to mirror dynamic value into the DOM/UI
- to change some attribute(s) of existing element(s)
- to generate elements itself dynamically – this covers conditions and loops
import { S } from "./esm-with-signals.js";
const count= S(0);
import { el } from "./esm-with-signals.js";
@@ -121,7 +121,7 @@ document.head.append(
const interval= 5 * 1000;
setTimeout(clearInterval, 10*interval,
setInterval(()=> count(count()+1), interval));
-
To derived attribute based on value of signal variable just use the signal as a value of the attribute (assign(element, { attribute: S('value') })
). assign
/el
provides ways to glue reactive attributes/classes more granularly into the DOM. Just use dedicated build-in attributes dataset
, ariaset
and classList
.
For computation, you can use the “derived signal” (see above) like assign(element, { textContent: S(()=> 'Hello '+WorldSignal()) })
. This is read-only signal its value is computed based on given function and updated when any signal used in the function changes.
To represent part of the template filled dynamically based on the signal value use S.el(signal, DOMgenerator)
. This was already used in the todo example above or see:
import { S } from "./esm-with-signals.js";
+
To derived attribute based on value of signal variable just use the signal as a value of the attribute (assign(element, { attribute: S('value') })
). assign
/el
provides ways to glue reactive attributes/classes more granularly into the DOM. Just use dedicated build-in attributes dataset
, ariaset
and classList
.
For computation, you can use the “derived signal” (see above) like assign(element, { textContent: S(()=> 'Hello '+WorldSignal()) })
. This is read-only signal its value is computed based on given function and updated when any signal used in the function changes.
To represent part of the template filled dynamically based on the signal value use S.el(signal, DOMgenerator)
. This was already used in the todo example above or see:
import { S } from "./esm-with-signals.js";
const count= S(0, {
add(){ this.value= this.value + Math.round(Math.random()*10); }
});
@@ -147,4 +147,4 @@ setTimeout(clearInterval, 10*interval, setInterval(function(){
S.action(count, "add");
S.action(numbers, "push", count());
}, interval));
-
# Mnemonic
S(<value>)
— signal: reactive valueS(()=> <computation>)
— read-only signal: reactive value dependent on calculation using other signalsS.on(<signal>, <listener>[, <options>])
— listen to the signal value changesS.clear(...<signals>)
— off and clear signalsS(<value>, <actions>)
— signal: pattern to create complex reactive objects/arraysS.action(<signal>, <action-name>, ...<action-arguments>)
— invoke an action for given signalS.el(<signal>, <function-returning-dom>)
— render partial dom structure (template) based on the current signal value
\ No newline at end of file
+