簡單實現 vue 觀察者 模式 和 雙向綁定 【coding】

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, {
      // 作一下埋點
      set(v) {
        cache = v;
        _ob.notiy();
      },
      // 觸發watch 實例更新
      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);

demohtml

相關文章
相關標籤/搜索