Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

crutchcorn commented May 18, 2022

Super helpful suggestion from @edemaine

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

@edemaine
Copy link

edemaine commented May 18, 2022

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