先贴代码
let index = 0;
let watcherId = 0; // watcher标识
let hasWatcher = {}; // 将id为1的watcher加入queue,便是{1:true}
let queue = []; // 存放watcher
let waiting = false;
function nextTick (cb) {
setTimeout(cb, 2000);
}
class Watcher {
constructor () {
this.id = ++watcherId;
}
update () {
console.log('Watcher' + this.id + ' update');
watcherToQueue(this); // 将当前watcher放入队列中
}
run () {
console.log('Watcher' + this.id + '视图更新啦~');
}
}
function watcherToQueue(watcher) {
const id = watcher.id;
if (hasWatcher[id] == null) {
hasWatcher[id] = true;
queue.push(watcher);
if (!waiting) {
waiting = true;
nextTick(queueWatcherRun);
}
}
}
function queueWatcherRun () {
let watcher, id;
for (index = 0; index <