Last active
November 13, 2023 19:21
-
-
Save crutchcorn/f1b1dad6b3780024b67bfd61afc73152 to your computer and use it in GitHub Desktop.
A basic reproduction of how SolidJS's internal attribute reactivity works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let Listener = undefined; | |
function readSignal() { | |
if (Listener) { | |
this.observers.push(Listener) | |
} | |
return this.value; | |
} | |
function writeSignal(signal, value) { | |
signal.value = value; | |
signal.observers.forEach(observer => observer()) | |
} | |
function createSignal(value) { | |
const s = { | |
value, | |
observers: [] | |
}; | |
const setter = (val) => { | |
return writeSignal(s, val); | |
}; | |
return [readSignal.bind(s), setter]; | |
} | |
const [num, setNum] = createSignal(0); | |
function ElementBoundFn() { | |
// This might be something like `boundElement.setAttribute('value', num())` IRL | |
console.log(num()); | |
} | |
Listener = ElementBoundFn | |
ElementBoundFn() | |
Listener = undefined | |
setNum(100); | |
setNum(0); |
I was trying to be fancy and make each execution of the effect function redetect dependencies and depend on them (as Solid does). But in hindsight, because this code doesn't have any cleanup yet, this is problematic: it will register with the same signals multiple times. So it might be better for purpose of simple explanation to just detect deps in the first run, like so:
function createEffect(fn) {
const oldListener = Listener;
Listener = fn;
fn();
Listener = oldListener;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Super helpful suggestion from @edemaine