乐趣区

关于vue.js:简单实现-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);

demo

退出移动版