简介

观察者模式是一种一对多的关系设计方案,一旦有变化发生,所有的订阅者都会响应。

  1. const Event = function() {
  2. let clientList = {}
  3. let listen = null
  4. let trigger = null
  5. let remove = null
  6. listen = function(key, fn) {
  7. const fns = clientList[key]
  8. if(!fns) {
  9. clientList[key] = []
  10. }
  11. clientList[key].push(fn)
  12. }
  13. trigger = function(key, message) {
  14. const fns = clientList[key]
  15. if(!fns) return false
  16. for(let i = 0, len = fns.length; i < len; i++) {
  17. const fn = fns[i]
  18. fn(message)
  19. }
  20. }
  21. remove = function(key, fn) {
  22. const fns = clientList[key]
  23. if(!fns) return false
  24. if(!fn) {
  25. clientList[key] = []
  26. } else {
  27. for(let i = 0, len = fns.length; i++) {
  28. const _fn = fns[i]
  29. if(_fn === fn) {
  30. fns.splice(i, 1)
  31. }
  32. }
  33. }
  34. }
  35. return {
  36. listen: listen,
  37. trigger: trigger,
  38. remove: remove
  39. }
  40. }

Vue中的订阅者模式

订阅者 Dep

  1. class Dep {
  2. constructor(){
  3. this.subs = []
  4. }
  5. addSub(sub) {
  6. this.subs.push(sub)
  7. }
  8. notify() {
  9. this.subs.forEach(sub => {
  10. sub.update()
  11. })
  12. }
  13. }

观察者Watcher

  1. class Watcher {
  2. constructor() {
  3. Dep.target = this
  4. }
  5. update() {
  6. }
  7. }

依赖收集 Observer

  1. function Observer(obj) {
  2. Object.keys(obj).forEach(key => {
  3. let val = obj[key]
  4. const dep = new Dep()
  5. Object.defineProperty(obj, key , {
  6. enumerable: true,
  7. configurable: true,
  8. get: function reactiveGetter() {
  9. dep.addSub(Dep.target) // 把watch对象存储到dep的subs中
  10. return val
  11. }
  12. ,
  13. set: function(newVal) {
  14. if(val === newVal) return
  15. val = newVal
  16. // 在set的时候触发更新
  17. dep.notify()
  18. }
  19. })
  20. }