solidjs

字数 267 · 2022-08-31

Granular updates enabled by solid’s compiler.

Core mechanism

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const context = [];

function getCurrentObserver() {
  return context[context.length - 1];
}

export function createEffect(fn) {
  const execute = () => {
    context.push(execute);
    try {
      fn();
    } finally {
      context.pop();
    }
  }
  execute();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export function createSignal(value) {
  const subscribers = new Set();

  const read = () => {
    const current = getCurrentObserver();
    if (current) subscribers.add(current);
    return value;
  };

  const write = (nextValue) => {
    value = nextValue;
    for (const sub of subscribers) {
      sub();
    }
  };

  return [read, write]; 
}