vue 原理解析:

1、实现一个数据监听器Observer,能够对数据对象的所有属性进行监听,如有变动可拿到最新值并通知订阅者
2、实现一个指令解析器Compile,对每个元素节点的指令进行扫描和解析,根据指令模板替换数据,以及绑定相应的更新函数
3、实现一个Watcher,作为连接Observer和Compile的桥梁,能够订阅并收到每个属性变动的通知,执行指令绑定的相应回调函数,从而更新视图
4、mvvm入口函数,
实现一个MVVM和promise

<input id="input"/>

const data = {};
const input = document.getElementById('input');
Object.defineProperty(data, 'text', {
  set(value) {
    input.value = value;
    this.value = value;
  }
});
input.onChange = function(e) {
  data.text = e.target.value;
}

实现一个promise

我们用的 new Promise(function(resolve, reject) {}) 回调函数中有两个 参数 resolve,reject

1.要有一个状态参数 state,pending, fulfilled,rejected
2.一个 then 方法,一个 resolve 方法,一个 reject 方法
3.then 中根据状态判断执行不同的操作,需要一个成功时的回调

function newPromise(fn) {
  
  let doneList = [];
  let state = 'pending';
  // 加入链式,成功回调的方法就得变成数组才能存储
  this.then(function(done){
    // 加入状态机制
    switch(state) {
      case 'pending':
         doneList.push(done);
         return this;
         break;
      case 'fulfilled':
        done();
        return this;
        break;
    }
  })


  function resolve(newVal) {
    
    state = 'fulfilled';
    setTimeout( function{
      let value = newVal;
      // 加上异步结果的传递
      //doneList.forEach(function(fulfill){
      // value = fulfill(value)
      //})
      =====================
      // 支持串行
      //执行resolve时,我们会尝试将doneList数组中的值都执行一遍
      //当遇到正常的回调函数的时候,就执行回调函数
      //当遇到一个新的promise的时候,就将原doneList数组里的回调函数推入新的promise的doneList,以达到循环的目的
      for (let i = 0;i<doneList.length;i++){
        let temp = doneList[i](value)
        if(temp instanceof newPromise){
            let newP =  temp;
            for(i++;i<doneList.length;i++){
                newP.then(doneList[i]);
            }
        }else{
            value = temp;
        }
      }
     },0)
  }
  
  // 加入reject
  function reject(newValue){
    state = "rejected";
    setTimeout(function(){
      var value = newValue;
      var tempRe = failList[0](value);
      //如果reject里面传入了一个promise,那么执行完此次的fail之后,将剩余的done和fail传入新的promise中
      if(tempRe instanceof newPromise){
        var newP = tempRe;
        for(i=1;i<doneList.length;i++){
            newP.then(doneList[i],failList[i]);
        }
      }else{
        //如果不是promise,执行完当前的fail之后,继续执行doneList
        value =  tempRe;
        doneList.shift();
        failList.shift();
        resolve(value);
      }
    },0);
  }
  fn(resolve,reject)
}

相关文章: