发布订阅模式(Pub-Sub Pattern)
发布订阅模式由发布者、订阅者、事件中心三部分组成
- 使用场景:跨组件数据传递
// 事件中心
class EventBus {
constructor() {
this.subs = Object.create(null)
}
// 订阅的方法
on (eventName, cb) {
this.subs[eventName] = this.subs[eventName] || []
this.subs[eventName].push(cb)
}
// 发布的方法
emit (eventName, value) {
this.subs[eventName] && this.subs[eventName].forEach(cb => cb(value))
}
}
const eventBus = new EventBus()
// 订阅者
eventBus.on('yw', (res) => {
console.log('res: ', res);
})
// 发布者
eventBus.emit('yw', '999')
观察者模式(Observer Pattern)
观察者模式由发布者、观察者两部分组织 发布者负责添加需要观察的观察者,当数据变化时再通知所有添加的观察者 观察者负责更新数据
- 使用场景:数据监听
// 观察者
class Watcher {
update (data) {
// 更新数据
console.log(data)
}
}
// 发布者
class Dep {
constructor() {
this.subs = []
}
// 添加观察者
add (watcher) {
watcher && watcher.update && this.subs.push(watcher)
}
// 通知观察者
notify () {
this.subs.forEach(watcher => {
watcher.update()
})
}
}