[Signal] 1 - Basic version of signal
Implement two functions of Signals
createSignal
: return a tuple with read function and wrtie functioncreateEffect
: accept a function which will be executed when signal value changed
Code to test:
import { createSignal } from "./reactivy";
const [count, setCount] = createSignal(0);
console.log(count()); // 0
setCount(5);
console.log(count()); // 5
Version 1 - CreateSignal
export function createSignal(value) {
const read = () => value;
const write = (newValue) => {
value = newValue;
};
return [read, write];
}
Version 2 - CreateSignal & CreateEffect
Code to test:
import { createSignal, createEffect } from "./reactivy";
const [count, setCount] = createSignal(0);
createEffect(() => {
console.log(count());
});
setCount(5);
stack
: global state, everytimecreateEffect
is called, will be added intostack
subscribers
: forread
function, geteffect
, add tosubscribers
, so that when value change, can notify signals
const stack = []
export function createSignal(value) {
const subscribers = new Set();
const read = () => {
// check is there any effect runnning?
// if yes, then add to subscribers
const observer = stack[stack.length - 1];
if (observer) {
subscribers.add(observer);
}
return value;
};
const write = (newValue) => {
value = newValue;
// notify all the subscribers there is changes
for (const observer of subscribers) {
// add effect to the stack again
observer.execute();
}
};
return [read, write];
}
export function createEffect(fn) {
const effect = {
execute() {
stack.push(effect);
fn();
stack.pop();
}
};
effect.execute();
}
分类:
Compose
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-10-05 [RxJS] Defer task execution with the asapScheduler (microtask)
2022-10-05 [Typescript] 42. Medium - Remove Index Signature
2020-10-05 [Typescript] Performance Bundling and tslib
2020-10-05 [Typescript] Enforcing Code Quality
2020-10-05 [Typescript] Understanding “lib” and ES libraries
2020-10-05 [Typescript] Configuration Inheritance with Extends
2018-10-05 [React] {svg, css module, sass} support in Create React App 2.0