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";
// α — `signal` represents a reactive value
const signal= S(0);
// β — just reacts on signal changes
S.on(signal, console.log);
// γ — just updates the value
const update= ()=> signal(signal()+1);
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";
const signal= S(0);
// computation pattern
const double= S(()=> 2*signal());
const ac= new AbortController();
S.on(signal, v=> console.log("signal", v), { signal: ac.signal });
S.on(double, v=> console.log("double", v), { signal: ac.signal });
signal(signal()+1);
const interval= 5 * 1000;
const id= setInterval(()=> signal(signal()+1), interval);
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";
const signal= S(0, {
increaseOnlyOdd(add){
console.info(add);
if(add%2 === 0) return this.stopPropagation();
this.value+= add;
}
});
S.on(signal, console.log);
const oninterval= ()=>
S.action(signal, "increaseOnlyOdd", Math.floor(Math.random()*100));
const interval= 5*1000;
setTimeout(
clearInterval,
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";
const todos= S([], {
push(item){
this.value.push(S(item));
},
pop(){
const removed= this.value.pop();
if(removed) S.clear(removed);
},
[S.symbols.onclear](){ // this covers `O.clear(todos)`
S.clear(...this.value);
}
});
import { el, on } from "./esm-with-signals.js";
/** @type {ddeElementAddon<HTMLFormElement>} */
const onsubmit= on("submit", function(event){
event.preventDefault();
const data= new FormData(this);
switch (data.get("op")){
case "A"/*dd*/:
S.action(todos, "push", data.get("todo"));
break;
case "E"/*dit*/: {
const last= todos().at(-1);
if(!last) break;
last(data.get("todo"));
break;
}
case "R"/*emove*/:
S.action(todos, "pop");
break;
}
});
document.body.append(
el("ul").append(
S.el(todos, todos=>
todos.map(textContent=> el("li", textContent)))
),
el("form", null, onsubmit).append(
el("input", { type: "text", name: "todo", placeholder: "Todo’s text" }),
el(radio, { textContent: "Add", checked: true }),
el(radio, { textContent: "Edit last" }),
el(radio, { textContent: "Remove" }),
el("button", "Submit")
)
);
document.head.append(
el("style", "form{ display: flex; flex-flow: column nowrap; }")
);
function radio({ textContent, checked= false }){
return el("label").append(
el("input", { type: "radio", name: "op", value: textContent[0], checked }),
" ",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";
const count= S(0);
import { el } from "./esm-with-signals.js";
document.body.append(
el("p", S(()=> "Currently: "+count())),
el("p", { classList: { red: S(()=> count()%2) }, dataset: { count }, textContent: "Attributes example" })
);
document.head.append(
el("style", ".red { color: red; }")
);
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";
const count= S(0, {
add(){ this.value= this.value + Math.round(Math.random()*10); }
});
const numbers= S([ count() ], {
push(next){ this.value.push(next); }
});
import { el } from "./esm-with-signals.js";
document.body.append(
S.el(count, count=> count%2
? el("p", "Last number is odd.")
: el()
),
el("p", "Lucky numbers:"),
el("ul").append(
S.el(numbers, numbers=> numbers.toReversed()
.map(n=> el("li", n)))
)
);
const interval= 5*1000;
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