var id = 0;function Dep(){ this.id = id++; this.subs = [];}Dep.prototype.addSub = function(watcher){ this.subs.push(watcher);}Dep.prototype.depend = function(){ if(Dep.target){ Dep.target.addDep(this); }}Dep.prototype.remove = function(sub){ this.subs.splice(this.subs.indexOf(sub),1);}let stacks = [];// 存放watcherfunction pushTarget (watcher){ Dep.target = watcher; stack.push(watcher);}function popTarget(){ stack.pop(); Dep.target = stack[stack.length-1]}
var id = 0, callbacks = [], queue = [], has = {};function Watcher(vm,exprOrFn,cb,opts){ this.id = id++; this.vm = vm; cb = typeof cb ==='function'?cb:function(){}; if(typeof exprOrFn === 'function'){ this.getter = exprOrFn; } this.deps=[]; this.depIds = new Set(); this.opts = opts; this.get();}// 在watcher中添加depWatcher.prototype.addDep = function(dep){ var id = dep.id; if(!this.depIds.has(id)){ this.deps.push(dep); this.depIds.add(id); // 在dep中添加watcher dep.addSub(this); }}Watcher.prototype.get = function(){ pushTarget(); this.getter(); popTarget();}Watcher.prototype.update = function (){ queueWatcher(this);}Watcher.prototype.run = function(){ this.get();}function queueWatcher(vm){ var id = vm.id; if(!has[id]){ queue.push(vm); has[id] = true; nextTick(flushQue) }}// 清空队列function flushQue(){ queue.forEach(watcher=>wathcer.run()); queue = []; has = {};}function nextTick(cb){ callbacks.push(cb); let timerFunction = ()=>{ flushCallBacks(); } if(Promise){ return Promise.resolve().then(timerFunction); } if(MutationOberserver){ let observe = new MutationObserver(timerFunction); let textNode = document.createTextNode(10); observe.observe(textNode,{charactorData:true}); textNode.textContent = 20; return true } if(setImmediate){ return setImmediate(timerFunction) } setTimeout(timerFunction,0);}