【vue2原理】-第一篇,发布订阅模式和观察者模式

123 阅读1分钟

1. 发布订阅模式

  • 订阅者
  • 发布者
  • 信号中心
class EventEmitter {
    constructor() {
        this.subs = Object.create(null)
    }
    
    $on(eventType, handler) {
        this.subs[eventType] = this.subs[eventType] || []
        this.subs[eventType].push(handler)
    }
    
    $emit() {
        let eventType = Array.prototype.shift.call( arguments ), // 取出事件类型
        
        if(this.subs[eventType]) {
            this.subs[eventType].forEach(handler => {
                handler.apply( this, arguments );
            })
        }
    }
    
    $off(eventType, fn) {
        let fns = this.subs[eventType];
    
        if(!fns) {
          return false;
        }

        if(!fn) {
          fns && (fns.length = 0);
        } else {
          for(let j = fns.length - 1; j >= 0; j--) {
            let _fn = fns[j];
            if(_fn === fn) {
              fns.splice(j, 1)
            }
          }
        }
    }
}

2. 观察者模式

  • 订阅者(观察者) -- Watcher

    • update(): 当事件发生时,具体要做的事情
  • 发布者(目标) -- Dep

    • subs数组: 存储所有观察者
    • addSub(): 添加观察者
    • notify(): 当事件发生,调用所有观察者的update()方法
  • 没有事件中心

// 发布者-目标
class Dep {
    constructor() {
        this.subs = []
    }
    
    // 添加订阅者
    addSub(sub) {
        if(sub && sub.update) {
            this.subs.push(sub)
        }
    }
    
    // 发布通知
    notify() {
        this.subs.forEach(sub => {
            sub.update()
        })
    }
}

// 订阅者-观察者
class Watcher {
    update() {
        console.log('update')
    }
}

发布订阅模式.png