js-review/js/vue响应式原理/1-Reactivity.js
2024-06-01 04:29:31 +08:00

41 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const targetMap = new WeakMap() // 用原始对象作为key依赖映射作为value
function track(target, key) {
let depsMap = targetMap.get(target)
if(!depsMap) {
targetMap.set(target, (depsMap = new Map()))
}
let dep = depsMap.get(key)
if(!dep){
depsMap.set(key, (dep=new Set()))
}
dep.add(effect)
}
function trigger(target, key) {
const depsMap = targetMap.get(target)
if(!depsMap) return
const deps = depsMap.get(key)
deps.forEach(effect => {
effect()
});
}
// 测试
let product = {price: 5, quantity: 2}
let total = 0
let effect = ()=>{ // 副作用函数
total = product.price * product.quantity
}
track(product, 'quantity') // 跟踪这个key并记录副作用函数
effect() // 首次执行副作用函数
console.log(total);
product.quantity = 3
trigger(product, 'quantity') // 重新触发所有副作用
console.log(total);
/* 当数量发生变化时对应的total也要发生变化这个计算是由副作用函数负责计算的
只要保存这个副作用,当与之关联的数据发生变化时执行副作用就行了。
*/