let activeReactive = null;
// 2、响应式依赖类封装
class Depend {
constructor() {
this.reactiveFns = new Set();
}
notify() {
this.reactiveFns.forEach((fn) => {
fn();
});
}
depend() {
if (activeReactive) {
this.reactiveFns.add(activeReactive);
}
}
}
// 1、响应式函数封装
function watchFn(fn) {
activeReactive = fn;
fn();
activeReactive = null;
}
// 4、依赖收集的数据结构
const targetWeakMap = new WeakMap();
function getDepend(obj, key) {
let map = targetWeakMap.get(obj);
if (!map) {
map = new Map();
targetWeakMap.set(obj, map);
}
let depend = map.get(key);
if (!depend) {
depend = new Depend();
map.set(key, depend);
}
return depend;
}
// 3、自动监听对象变化
function reactive(obj) {
return new Proxy(obj, {
get: function (target, key, receiver) {
const depend = getDepend(target, key);
// depend.addDepend(activeReactive);
depend.depend();
return Reflect.get(target, key, receiver);
},
set: function (target, key, newVal, receiver) {
Reflect.set(target, key, newVal, receiver);
const depend = getDepend(target, key);
depend.notify();
},
});
}
const objProxy = reactive({
name: "zs",
age: 18,
});
watchFn(function foo() {
console.log("1111111111111111111111111-----------------", objProxy.name);
console.log("22222222222222222222222-----------------", objProxy.name);
console.log("33333333333333333333-----------------", objProxy.name);
console.log("4444444444444444444444444-----------------", objProxy.name);
});
watchFn(function () {
console.log("age变化1111111111111111", objProxy.age);
});
watchFn(function () {
console.log("age变化22222222222222222222222", objProxy.age);
});
function bar() {
console.log("普通函数-----------不执行-----------普通函数");
}
objProxy.name = "kobe";