var data = {
name: "fangtangxiansheng",
job: "fe",
power: 0
};
console.log(data);
let target = null;
class willObserver {
watchList = [];
// 增加观察者
addWatch() {
target && (this.watchList =[... new Set([...this.watchList, target])]);
}
watchUpdate() {
this.watchList.forEach((watch) => {
watch.update();
});
}
// 通知
notiy() {
this.watchUpdate();
}
}
class Watch {
constructor(cb) {
this.cb = cb;
target = this;
}
update() {
this.cb();
}
}
const creatWatch = (expCondition, cb) => {
new Watch(cb);
expCondition();
};
// 构造 ”数据依赖埋点“
const trasnfromDataToAutoListion = (data) => {
Object.keys(data).forEach((key) => {
let cache = data[key];
let _ob = new willObserver();
Object.defineProperty(data, key, {
// 触发watch 实例更新
set(v) {
cache = v;
_ob.notiy();
},
// 做一下埋点
get() {
_ob.addWatch();
return cache;
}
});
});
};
trasnfromDataToAutoListion(data);
creatWatch(
() => {
console.log("condition", data.name, data.job);
},
() => {
document.querySelector("#html").innerHTML = JSON.stringify(data);
}
);
document.querySelector("#html").innerHTML = JSON.stringify(data);
setInterval(() => {
data.power = `${Math.random() * 100}%`;
}, 500);
demo
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。