[Signal] 1 - Basic version of signal
Implement two functions of Signals
createSignal
: return a tuple with read function and wrtie functioncreateEffect
: accept a function which will be executed when signal value changed
Code to test:
import { createSignal } from "./reactivy";
const [count, setCount] = createSignal(0);
console.log(count()); // 0
setCount(5);
console.log(count()); // 5
Version 1 - CreateSignal
export function createSignal(value) {
const read = () => value;
const write = (newValue) => {
value = newValue;
};
return [read, write];
}
Version 2 - CreateSignal & CreateEffect
Code to test:
import { createSignal, createEffect } from "./reactivy";
const [count, setCount] = createSignal(0);
createEffect(() => {
console.log(count());
});
setCount(5);
stack
: global state, everytimecreateEffect
is called, will be added intostack
subscribers
: forread
function, geteffect
, add tosubscribers
, so that when value change, can notify signals
const stack = []
export function createSignal(value) {
const subscribers = new Set();
const read = () => {
// check is there any effect runnning?
// if yes, then add to subscribers
const observer = stack[stack.length - 1];
if (observer) {
subscribers.add(observer);
}
return value;
};
const write = (newValue) => {
value = newValue;
// notify all the subscribers there is changes
for (const observer of subscribers) {
// add effect to the stack again
observer.execute();
}
};
return [read, write];
}
export function createEffect(fn) {
const effect = {
execute() {
stack.push(effect);
fn();
stack.pop();
}
};
effect.execute();
}