Skip to content

Instantly share code, notes, and snippets.

@vikiboss
Created March 23, 2023 02:46
Show Gist options
  • Save vikiboss/9432c09c38c071f1e2bd5a805d40189b to your computer and use it in GitHub Desktop.
Save vikiboss/9432c09c38c071f1e2bd5a805d40189b to your computer and use it in GitHub Desktop.
mini signal implement
let currentListener: Function | undefined = undefined
function createSignal<T>(initialValue: T) {
let value = initialValue
const subscribers = new Set<Function>()
const read = () => {
if (currentListener !== undefined) {
subscribers.add(currentListener)
}
return value
}
const write = (newValue: T) => {
value = newValue
subscribers.forEach((fn: Function) => fn())
}
return [read, write] as const
}
function createEffect(callback: Function) {
currentListener = callback
callback()
currentListener = undefined
}
const [count, setCount] = createSignal(0)
createEffect(() => {
console.log(count())
})
setInterval(() => {
setCount(count() + 2)
}, 1000)
@vikiboss
Copy link
Author

vikiboss commented Mar 23, 2023

TypeScript version, inspired from SolidJS.

modified from: https://www.lksh.dev/blog/writing-your-own-reactive-signal-library

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