
这次我们要写观察者模式、上方的图只是为了表达观察者和发布订阅者模式的区别
观察者模式
// 观察者类class Observer{constructor(name, subject){this.name = name;this.subject = subject;this.subject.addObserver(this)}// 接收目标变化update(){console.log(`${this.name}:目标发生----变化了 ${this.subject.getState()}`)}}// 目标类class Subject{constructor(){this.observer = [];this.state = '0'}getState(){return this.state;}// 改变状态setState(state){this.state = state;// 通知观察者this.notifyAll()}// 添加观察者addObserver(observer){this.observer.push(observer);}// 通知观察者notifyAll(){this.observer.forEach( item => item.update())}}// 目标对象let subject = new Subject();// 观察者们let a = new Observer('a',subject)let b = new Observer('b',subject)let c = new Observer('c',subject)subject.setState('111')
观察者模式:观察者和目标直接进行交互、观察者直接订阅subject、当subect被激活的时候会触发观察者的监听事件
发布订阅模式
class EventBus{constructor(){this.callbacks = {}}$on(name,fn){if(!this.callbacks[name]) this.callbacks[name] = [];this.callbacks[name].push(fn);}$emit(name, arg){if(this.callbacks[name]){this.callbacks[name].forEach( cb => cb(arg))}}}let eventBus = new EventBus()// 页面1---添加event1的订阅eventBus.$on('event1',(arg)=>{console.log('页面1----event1变化了',arg)})// 页面2 ---添加event1的订阅eventBus.$on('event1',(arg)=>{console.log('页面2---event1变化了',arg)})// 五秒后发布通知setTimeout( () =>{eventBus.$emit('event1',{data:1111})}, 5000)
vue的数据双向绑定和事件总线就是使用这个模式、订阅者订阅某个事件名称标记、发布者直接携带参数广播事件!
