在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
最近更新
01
使用VSCode插件快速导航代码库:类似autojump的跳转功能
03-20
02
react事件系统
11-07
03
react学习-小册
11-04
更多文章>