当前位置:网站首页>track和trigger
track和trigger
2022-04-21 20:37:00 【hamimelon2020】
<!DOCTYPE html>
<html>
<head>
<title>document.write() Example</title>
</head>
<body>
<script type="text/javascript">
const data = {
ok:true, text:'hello world'}
const bucket = new WeakMap()
let activeEffect
function effect(fn) {
const effectFn = () => {
activeEffect = effectFn
fn()
}
effectFn.deps = []
effectFn()
}
const obj = new Proxy(data, {
get(target, key) {
// 收集副作用函数
track(target, key);
console.log(target[key])
return target[key]
},
set(target, key, newVal) {
target[key] = newVal;
// 取出副作用并执行
trigger(target, key);
}
})
// 封装track函数,追踪变化
function track(target, key) {
if (!activeEffect) return
let depsMap = bucket.get(target)
//console.log(depsMap)
console.log(bucket)
if (!depsMap) {
bucket.set(target, (depsMap = new Map()))
}
let deps = depsMap.get(key)
if (!deps) {
depsMap.set(key, (deps = new Set()))
}
deps.add(activeEffect)
activeEffect.deps.push(deps)
}
// 封装trigger函数,触发副总用函数重新执行
function trigger(target, key) {
const depsMap = bucket.get(target)
if (!depsMap) return
const effects = depsMap.get(key)
console.log(effects)
effects && effects.forEach(fn => fn())
}
effect(function effectFn(){
// console.log('effectFn');
document.body.innerText = obj.ok ? obj.text : 'not'
})
setTimeout(() => {
obj.ok = false // 打印 effectFn
},2000)
console.log(effects)
</script>
</body>
</html>
版权声明
本文为[hamimelon2020]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_40945354/article/details/124317991
边栏推荐
猜你喜欢

人机验证reCAPTCHA v3使用完备说明

C语言题目一:1,2,3,4能组成的三位数

神经网络 || 注意力机制的Pytorch代码实现

How chaotic is the research market

Actual combat | e-commerce business performance test (II): JMeter parameterization function realizes data-driven registration and login

Construction of distributed second kill system

Traceup | use project management software to help overcome procrastination

2022年电工(初级)考试模拟100题及模拟考试

Pytorch框架 || torch.nn.modules.Module(nn.Module)

如何确保API 的稳定性与正确性?你只需要这一招
随机推荐
Specific methods of configuring Profibus and PROFINET communication in two TIA botu projects
Mysql刷题题解_多表联查_运营想要计算一些参加了答题的不同学校、不同难度的用户平均答题量,请你写SQL取出相应数据
Complete collection of basic MySQL commands
2022-4-11至2022-4-17周报
C语言求完全平方数
Tracup|使用项目管理软件帮助战胜拖延症
<2021SC@SDUSC>山东大学软件工程应用与实践JPress代码分析(二)
单、双链表的循环链表(十五)
Mysql 基础命令大全
glew, glee與 gl glu glut glx glext的區別和關系
C语言题目一:1,2,3,4能组成的三位数
华融融达期货这家公司怎么样?期货开户办理安全吗?
异常处理器
Go语言自学系列 | golang init函数
Map&Set
Android Development Internship interview questions, Android development interview basis
RTMP(4):User Control Message
Construction of distributed second kill system
CUDA02 - 访存优化和Unified Memory
php UEditor上传文件(图片视频)到OSS