Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A basic reproduction of how SolidJS's internal attribute reactivity works
let Listener = undefined;
function readSignal() {
if (Listener) {
return this.value;
function writeSignal(signal, value) {
signal.value = value;
signal.observers.forEach(observer => observer())
function createSignal(value) {
const s = {
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
Listener = ElementBoundFn
Listener = undefined
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;
  Listener = oldListener;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment