watcher.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function Watcher(vm, expOrFn, cb) {
  2. this.cb = cb;
  3. this.vm = vm;
  4. this.expOrFn = expOrFn;
  5. this.depIds = {};
  6. if (typeof expOrFn === 'function') {
  7. this.getter = expOrFn;
  8. } else {
  9. this.getter = this.parseGetter(expOrFn.trim());
  10. }
  11. this.value = this.get();
  12. }
  13. Watcher.prototype = {
  14. update: function() {
  15. this.run();
  16. },
  17. run: function() {
  18. var value = this.get();
  19. var oldVal = this.value;
  20. if (value !== oldVal) {
  21. this.value = value;
  22. this.cb.call(this.vm, value, oldVal);
  23. }
  24. },
  25. addDep: function(dep) {
  26. // 1. 每次调用run()的时候会触发相应属性的getter
  27. // getter里面会触发dep.depend(),继而触发这里的addDep
  28. // 2. 假如相应属性的dep.id已经在当前watcher的depIds里,说明不是一个新的属性,仅仅是改变了其值而已
  29. // 则不需要将当前watcher添加到该属性的dep里
  30. // 3. 假如相应属性是新的属性,则将当前watcher添加到新属性的dep里
  31. // 如通过 vm.child = {name: 'a'} 改变了 child.name 的值,child.name 就是个新属性
  32. // 则需要将当前watcher(child.name)加入到新的 child.name 的dep里
  33. // 因为此时 child.name 是个新值,之前的 setter、dep 都已经失效,如果不把 watcher 加入到新的 child.name 的dep中
  34. // 通过 child.name = xxx 赋值的时候,对应的 watcher 就收不到通知,等于失效了
  35. // 4. 每个子属性的watcher在添加到子属性的dep的同时,也会添加到父属性的dep
  36. // 监听子属性的同时监听父属性的变更,这样,父属性改变时,子属性的watcher也能收到通知进行update
  37. // 这一步是在 this.get() --> this.getVMVal() 里面完成,forEach时会从父级开始取值,间接调用了它的getter
  38. // 触发了addDep(), 在整个forEach过程,当前wacher都会加入到每个父级过程属性的dep
  39. // 例如:当前watcher的是'child.child.name', 那么child, child.child, child.child.name这三个属性的dep都会加入当前watcher
  40. if (!this.depIds.hasOwnProperty(dep.id)) {
  41. dep.addSub(this);
  42. this.depIds[dep.id] = dep;
  43. }
  44. },
  45. get: function() {
  46. Dep.target = this;
  47. var value = this.getter.call(this.vm, this.vm);
  48. Dep.target = null;
  49. return value;
  50. },
  51. parseGetter: function(exp) {
  52. if (/[^\w.$]/.test(exp)) return;
  53. var exps = exp.split('.');
  54. return function(obj) {
  55. for (var i = 0, len = exps.length; i < len; i++) {
  56. if (!obj) return;
  57. obj = obj[exps[i]];
  58. }
  59. return obj;
  60. }
  61. }
  62. };