發布訂閱模式,基於一個主題/事件通道,希望接收通知的對象(subscriber)通過自定義事件訂閱主題,被激活事件對象(publisher)通過發布主題事件的方式被通知。
js中的事件監聽機制就是一種觀察者模式
export default class Oberver { // 定義一個事件容器 event = {} subscribe (type, fn) { // 消息類型不存在 if (typeof this.event[type] === 'undefined') { this.event[type] = [fn] // 存在,將fn推入事件隊列 } else { this.event[type].push(fn) } } publish (type, args = {}) { // 消息類型沒人訂閱 if (!this.event[type]) return let i = 0 let len = this.event[type].length for (; i < len; i++) { // 依次執行事件隊列(發布) this.event[type][i].call(this, {type, args}) } } }