Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Last active November 13, 2023 19:21
Show Gist options
  • Save crutchcorn/f1b1dad6b3780024b67bfd61afc73152 to your computer and use it in GitHub Desktop.
Save crutchcorn/f1b1dad6b3780024b67bfd61afc73152 to your computer and use it in GitHub Desktop.
A basic reproduction of how SolidJS's internal attribute reactivity works
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);
@crutchcorn
Copy link
Author

Super helpful suggestion from @edemaine

function createEffect(fn) {
  function run() {
    const oldListener = Listener;
    Listener = run;
    fn();
    Listener = oldListener;
  }
  run();
}

@edemaine
Copy link

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