vue响应式原理模拟实现

in JavaScript with 0 comment

vue2 响应式原理是建立在javascript订阅者模式和Object.defineProperty()的基础之上实现的,下边用代码模拟一下vue2的响应式原理的核心部分 (vue3响应式原理使用es6的proxy实现)

let data = { price: 5, quantity: 2 };
    let observer = null,
      total = 0;
    //观察者模式 [或发布者订阅模式]
    class Subject {
      constructor() {
        this.observers = [];
      }
      addObserver() {
        if (observer && !this.observers.includes(observer)) {
          this.observers.push(observer);
        }
      }
      notify() {
        this.observers.forEach((observer) => {
          observer();
        });
      }
    }

    Object.keys(data).forEach((key) => {
      let interval = data[key];
      const subject = new Subject();
      Object.defineProperty(data, key, {
        get() {
          subject.addObserver();
          return interval;
        },
        set(newVal) {
          interval = newVal;
          //通知watcher
          subject.notify();
        }
      });
    });
    function watcher(fn) {
      observer = fn;
      observer();
    }
    //每个data实例都对应一个watcher
    watcher(() => {
      total = data.price * data.quantity;
    });
评论已关闭.