Created
December 14, 2023 21:56
-
-
Save metruzanca/0775ea7cf1f7a974e78f301977efac85 to your computer and use it in GitHub Desktop.
Basic signal implementation from a Ryan Carnianto Talk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const context: Function[] = [] | |
function getCurrentObserver() { | |
return context[context.length - 1] | |
} | |
function createEffect(fn: Function, name: string) { | |
const execute = () => { | |
context.push(execute) | |
try { | |
fn() | |
} finally { | |
context.pop() | |
} | |
} | |
execute() | |
} | |
function createSignal<T = any>(value: T) { | |
const subscribers = new Set<Function>() | |
const read = () => { | |
const current = getCurrentObserver() | |
if (current) subscribers.add(current) | |
return value | |
} | |
const write = (nextValue: T) => { | |
value = nextValue | |
for (const sub of subscribers) sub() | |
} | |
return [read, write] as const | |
} | |
// ----- | |
const [friend, setFriend] = createSignal('Sam') | |
const [age, setAge] = createSignal(100) | |
const greeting = () => `${friend()} is ${age()}` | |
createEffect(() => { | |
console.log(friend()) | |
}, 'name') | |
createEffect(() => { | |
console.log(age()) | |
}, 'age') | |
createEffect(() => { | |
console.log(greeting()) | |
}, 'greet') | |
setFriend('Jon') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment