diff options
| author | ivar <i@oiee.no> | 2025-12-02 18:46:19 +0100 |
|---|---|---|
| committer | ivar <i@oiee.no> | 2025-12-02 18:46:19 +0100 |
| commit | 8215d60f8e26fadbb96c6ca03973fd47f7a7eb28 (patch) | |
| tree | ba46ea72b11a23c839a958160cce4e3de9dea4b7 /index.js | |
| download | ueb-master.tar.xz ueb-master.zip | |
Diffstat (limited to 'index.js')
| -rw-r--r-- | index.js | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/index.js b/index.js new file mode 100644 index 0000000..e98a636 --- /dev/null +++ b/index.js @@ -0,0 +1,61 @@ +// Credit Ryan Carniato https://frontendmasters.com/courses/reactivity-solidjs/ + +let context = []; + +export function untrack(fn) { + const prevContext = context; + context = []; + const res = fn(); + context = prevContext; + return res; +} + +function cleanup(observer) { + for (const dep of observer.dependencies) { + dep.delete(observer); + } + observer.dependencies.clear(); +} + +function subscribe(observer, subscriptions) { + subscriptions.add(observer); + observer.dependencies.add(subscriptions); +} + +export function createSignal(value) { + const subscriptions = new Set(); + + const read = () => { + const observer = context[context.length - 1] + if (observer) subscribe(observer, subscriptions); + return value; + } + const write = (newValue) => { + value = newValue; + for (const observer of [...subscriptions]) { + observer.execute(); + } + } + + return [read, write]; +} + +export function createEffect(fn) { + const effect = { + execute() { + cleanup(effect); + context.push(effect); + fn(); + context.pop(); + }, + dependencies: new Set() + } + + effect.execute(); +} + +export function createMemo(fn) { + const [signal, setSignal] = createSignal(); + createEffect(() => setSignal(fn())); + return signal; +} |
