[SolidJS] Build a simple version of reactivity

let context = []

function cleanup(observer) {
  for (const dep of observer.dependencies) {
    dep.delete(observer)
  }
}

function subscribe(observer, subscriptions) {
  subscriptions.add(observer)
  observer.dependencies.add(subscriptions)
}

function untrack(fn) {
  const prevContext = context
  context = []
  const res = fn()
  context = prevContext
  return res
}

function createSignal<T = any>(value: T) {
  const subscriptions = new Set()
  const read = () => {
    const observer = context[context.length - 1]
    if (observer) subscribe(observer, subscriptions)
    return value
  };
  const write = (newValue: any) => {
    value = newValue
    for (const observer of [...subscriptions]) {
      observer.execute()
    }
  };

  return [read, write];
}

function createEffect(fn: () => void) {
  const effect = {
    execute() {
      cleanup(effect)
      context.push(effect)
      fn()
      context.pop()
    },
    dependencies: new Set()
  }
  context.push({execute: fn})
  effect.execute()
}

function createMemo(fn) {
  const [singal, setSingal] = createSignal()
  createEffect(() => {
    setSingal(fn())
  })
  return singal
}

const [count, setCount] = createSignal(0);
const [count2, setCount2] = createSignal(2);
const [show, setShow] = createSignal(true);

const sum = createMemo(() => {
  return count() + count2()
})

createEffect(() => {
  console.log(untrack(() => count()))
  //console.log(count(), count2(), sum())
  // if (show()) console.log(count())
  // else console.log(count2())
})


setShow(false)
setCount(10)
setCount(20)

 

posted @   Zhentiw  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-01-24 [TypeScript] Infer the Return Type of a Generic Function Type Parameter
2018-01-24 [MST] Derive Information from Models Using Views
2018-01-24 [TypeScript] Asynchronous Iteration using for-await-of
2018-01-24 [Typescript] Promise based delay function using async / await
2017-01-24 [Vue] Dynamic Vue.js Components with the component element
2017-01-24 [Vue] Parent and Child component communcation
2017-01-24 [Vue] Conditionally Render DOM Elements in Vue.js (v-if v-else v-show)
点击右上角即可分享
微信分享提示