mini signal implement
This file contains 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TypeScript version, inspired from SolidJS.