批量异步更新策略。

什么叫批量异步更新?

假设你每次setter触发某个数据的时候,对应的Watcher对象会被放入一个队列中,等到下一次tick的时候,将队列中的Watcher对象全部拿出来执行。(关于Watcher在我的另一篇文章有介绍(收集依赖))。

第一个tick:执行全局的script代码开始。UI render结束,本轮tick也就结束了。

举个关于批量异步更新的例子:

let has = {}; // 用来判断是否存在相同的watcher
let queue = []; // 可以理解为队列的容器
let watitng = false; // 一个标记,标记是否已经向nextTick()传递了flushSchedulerQueue()
function queueWatecher(watcher){
   const id = watcher.id;
   if(has[id]==null){
      has[id] = true;
      queue.push(watcher);
      // 取反为true,可以执行如下,执行完成后变为true,这时候想再次进来条件已经不再满足。
      // 所以这里无论你调用几次,终究只会执行一次
      if(!watitng){  
        nextTick(flushSchedulerQueue);
        watitng = true; // 这时传递了之后已经变为true
     }
   }
}

let callbackArr  = []; // 容器,用来储存传过来的值
let pending = false; // 一个标记位,表示一个等待的状态
function nextTick(cb){
  callbackArr.push(cb);
  // 执行完成为true,不再执行。
  if(!pending){
    setTimeout(flushCallbacks,0); // 异步执行
    pending = true;
  }
}	
function flushCallbacks(){
  for(let i=0;i<callbackArr.length;i++){
    callbackArr[i](); // 执行队列中所有run
  }
  callbackArr.length = 0; // 执行完清空
}
function flushSchedulerQueue(){
  for(i = 0;i<queue.length;i++){
    queue[i].run(); // 队列中的所有run方法
    has[queue[i].id] = null; // has中之前存好的true现在全部清空
   }
}
let uid = 0;
class Watcher{
  constructor(){
   // 只是用来标记每个Watcher对象,不要想太多
    this.id = ++uid; 
  }
  // 修改数据后被调用,触发run()
  update(){
   console.log('watcher'+this.id);
   queueWatecher(this);
  }
  // 触发视图更新
  run(){
   console.log(this.id+'视图更新了!');
  }
}
let w1 = new Watcher();
let w2 = new Watcher();
w1.update();
w2.update();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值