1. var id = 0;
    2. function Dep(){
    3. this.id = id++;
    4. this.subs = [];
    5. }
    6. Dep.prototype.addSub = function(watcher){
    7. this.subs.push(watcher);
    8. }
    9. Dep.prototype.depend = function(){
    10. if(Dep.target){
    11. Dep.target.addDep(this);
    12. }
    13. }
    14. Dep.prototype.remove = function(sub){
    15. this.subs.splice(this.subs.indexOf(sub),1);
    16. }
    17. let stacks = [];// 存放watcher
    18. function pushTarget (watcher){
    19. Dep.target = watcher;
    20. stack.push(watcher);
    21. }
    22. function popTarget(){
    23. stack.pop();
    24. Dep.target = stack[stack.length-1]
    25. }
    1. var id = 0,
    2. callbacks = [],
    3. queue = [],
    4. has = {};
    5. function Watcher(vm,exprOrFn,cb,opts){
    6. this.id = id++;
    7. this.vm = vm;
    8. cb = typeof cb ==='function'?cb:function(){};
    9. if(typeof exprOrFn === 'function'){
    10. this.getter = exprOrFn;
    11. }
    12. this.deps=[];
    13. this.depIds = new Set();
    14. this.opts = opts;
    15. this.get();
    16. }
    17. // 在watcher中添加dep
    18. Watcher.prototype.addDep = function(dep){
    19. var id = dep.id;
    20. if(!this.depIds.has(id)){
    21. this.deps.push(dep);
    22. this.depIds.add(id);
    23. // 在dep中添加watcher
    24. dep.addSub(this);
    25. }
    26. }
    27. Watcher.prototype.get = function(){
    28. pushTarget();
    29. this.getter();
    30. popTarget();
    31. }
    32. Watcher.prototype.update = function (){
    33. queueWatcher(this);
    34. }
    35. Watcher.prototype.run = function(){
    36. this.get();
    37. }
    38. function queueWatcher(vm){
    39. var id = vm.id;
    40. if(!has[id]){
    41. queue.push(vm);
    42. has[id] = true;
    43. nextTick(flushQue)
    44. }
    45. }
    46. // 清空队列
    47. function flushQue(){
    48. queue.forEach(watcher=>wathcer.run());
    49. queue = [];
    50. has = {};
    51. }
    52. function nextTick(cb){
    53. callbacks.push(cb);
    54. let timerFunction = ()=>{
    55. flushCallBacks();
    56. }
    57. if(Promise){
    58. return Promise.resolve().then(timerFunction);
    59. }
    60. if(MutationOberserver){
    61. let observe = new MutationObserver(timerFunction);
    62. let textNode = document.createTextNode(10);
    63. observe.observe(textNode,{charactorData:true});
    64. textNode.textContent = 20;
    65. return true
    66. }
    67. if(setImmediate){
    68. return setImmediate(timerFunction)
    69. }
    70. setTimeout(timerFunction,0);
    71. }