什么叫批量异步更新?
假设你每次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();