[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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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)