3
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


方糖先生
1.1k 声望1.8k 粉丝