Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. class Dep {
  2. constructor() {
  3. this.deps = [];
  4. }
  5.  
  6. static target = null;
  7.  
  8. depend() {
  9. if (Dep.target && this.deps.indexOf(Dep.target) === -1) {
  10. this.deps.push(Dep.target)
  11. }
  12. }
  13. notify() {
  14. this.deps.forEach((dep) => { dep() })
  15. }
  16. }
  17.  
  18. class Observable {
  19. constructor(obj) {
  20. return this.walk(obj)
  21. }
  22. defineReactive(obj, key, val) {
  23. const dep = new Dep();
  24. Object.defineProperty(obj, key, {
  25. get() {
  26. dep.depend();
  27. return val;
  28. },
  29. set(newVal) {
  30. val = newVal;
  31. dep.notify()
  32. }
  33. })
  34. }
  35. walk(obj) {
  36. Object.keys(obj).forEach(key => { this.defineReactive(obj, key, obj[key]) })
  37. return obj;
  38. }
  39. }
  40.  
  41. class Watcher {
  42. constructor(obj, key, cb, onUpdate) {
  43. this.obj = obj;
  44. this.key = key;
  45. this.cb = cb;
  46. this.onUpdate = onUpdate;
  47. return this.defineComputedReative();
  48. }
  49. defineComputedReative() {
  50. const self = this;
  51. const onDepUpdate = () => {
  52. console.log('1111')
  53. self.onUpdate(self.cb());
  54. }
  55. Object.defineProperty(self.obj, self.key, {
  56. get() {
  57. Dep.target = onDepUpdate;
  58. const value = self.cb();
  59. Dep.target = null;
  60. return value;
  61. }
  62. })
  63. }
  64. }
  65.  
  66.  
  67. function defineReactive(obj, key, val) {
  68. const deps = [];
  69. Object.defineProperty(obj, key, {
  70. get() {
  71. if (Dep.target && deps.indexOf(Dep.target) === -1) {
  72. deps.push(Dep.target)
  73. }
  74. console.log(`访问了${key}属性`)
  75. return val
  76. },
  77. set(newVal) {
  78. console.log(`${key}被修改了`)
  79. val = newVal
  80. deps.forEach(dep => { dep() })
  81. }
  82. })
  83. }
  84.  
  85.  
  86.  
  87. // function observable(obj) {
  88. // Object.keys(obj).forEach((key) => {
  89. // defineReactive(obj, key, obj[key]);
  90. // })
  91. // return obj;
  92. // }
  93.  
  94. // var person = {
  95. // firstName: 'H',
  96. // lastName: 'Y'
  97. // }
  98.  
  99. // var p = observable(person)
  100.  
  101. // function watcher(obj, key, cb) {
  102. // const onDepUpdate = () => {
  103. // const val = cb();
  104. // console.log('依赖更新了')
  105. // }
  106. // Object.defineProperty(obj, key, {
  107. // get() {
  108. // Dep.target = onDepUpdate;
  109. // const value = cb();
  110. // Dep.target = null
  111. // return value;
  112. // },
  113. // set() {
  114.  
  115. // }
  116. // })
  117.  
  118. // }
  119.  
  120. // watcher(p, 'fullName', () => {
  121. // return p.lastName + p.firstName
  122. // })
  123.  
  124. // console.log(p.fullName)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement