发布者与订阅者之间解耦,订阅者与订阅者之间也解耦。有新的订阅者,他只需要直接订阅事件,而不需要修改现有的代码。当然,为了完成发布-订阅系统,还需要实现一个事件订阅和分发系统,可以这样写:
以天气观测站为例,不同的人都订阅了天气观测的通知,当天气观测站发布天气警告的通知后,不同的人针对该通知做出不同的反应:建筑工地停止施工、船舶停在港口不出海、游客取消行程… 各个订阅者之间是独立的,他们针对通知做出的动作也是独立的
const EventEmit = function(){
this.events = {}
this.on = function(name, cb) {
if(this.events[name]) {
this.events[name].push(cb)
} else {
this.events[name] = [cb]
}
}
this.trigger = function(name, ...args) {
if(this.events[name]) {
this.events[name].forEach(eventListener => {
eventListener(...args)
})
}
}
}
let weatherEvent = new EventEmit();
weatherEvent.on('warning', function() {
console.log('buildingsite stop work')
})
weatherEvent.on('warning', function() {
console.log('ships mooring')
})
weatherEvent.on('warning', function() {
console.log('tourists canceltrip')
})
...
weatherEvent.trigger('warning')