Skip to content

Instantly share code, notes, and snippets.

@metruzanca
Created December 14, 2023 21:56
Show Gist options
  • Save metruzanca/0775ea7cf1f7a974e78f301977efac85 to your computer and use it in GitHub Desktop.
Save metruzanca/0775ea7cf1f7a974e78f301977efac85 to your computer and use it in GitHub Desktop.
Basic signal implementation from a Ryan Carnianto Talk
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