在js中实现响应式(原理参考solidjs)
在js中使用两个函数实现一个响应式数据
// createSignal.js
function createSignal(initialValue) {
let value = initialValue
const subscribe = new Set()
const read = () => {
if (currentListener !== undefined) {
subscribe.add(currentListener)
}
return value
}
const write = (newValue) => {
value = newValue
subscribe.forEach(fn => fn())
}
return [read, write]
}
// createEffect
let currentListener = undefined
function createEffect(callback) {
currentListener = callback
callback()
currentListener = undefined
}
# 使用示例
const [count, setCount] = createSignal(0)
createEffect(() => {
console.log(count())
})
createEffect(() => {
console.log(count(), Date.now())
})
setInterval(() => {
setCount(count() + 1)
}, 1000)
上次更新: 2023/03/21, 15:28:07