两种模式都是为了实现对象间的一种一对多的依赖关系。
观察者模式:订阅者和订阅目标是联系在一起的,订阅者发生变化,逐个通知订阅目标。
发布订阅模式:也是观察者模式的一种,但发布订阅模式中发布者和订阅者并不知道彼此的存在,消息不会直接发送给订阅者,而是由一个消息中心或者叫做调度中心,将过滤后的消息发送给所有的订阅者。
两种模式的区别就在于发布订阅模式有一个消息中心进行消息的过滤和分发。
/**
* 发布订阅者
* 支持事件监听、移除、单次监听、监听事件数量限制
*/
class EventBus {
constructor(options = {}) {
const { maxLength } = options;
this.events = Object.create(null);
this.maxLength = maxLength ?? Infinity;
}
on(eventName, fn) {
if (!fn) {
throw Error('fn is must');
return;
}
const _events = (this.events[eventName] = this.events[eventName] ?? []);
if (_events.length > this.maxLength) {
throw Error(`event ${eventName} has over maxlength ${this.maxLength}`);
return;
}
_events.push(fn);
}
emit(eventName, fn) {
const _events = this.events[eventName];
if (!_events) {
throw Error(`${eventName} is not listening on`);
return;
}
// fn存在,只执行对应函数
if (fn) {
const _fn = _events.filter(cb => fn === cb)[0];
_fn.apply(null, arguments);
return this;
}
// fn不存在,执行所有事件
_events.forEach(cb => {
cb.apply(this, arguments);
});
return this;
}
off(eventName, fn) {
const _events = this.events[eventName];
if (!_events) {
throw Error(`event ${eventName} is not listening`);
return;
}
// 如果事件参数存在,代表只移除指定的一个事件
if (fn) {
const _fns = _events.filter(cb => fn !== cb);
this.events[eventName] = _fns;
return this;
}
// fn不存在,说明是移除事件名对应的所有事件
this.events[eventName] = null;
delete this.events[eventName];
return this;
}
once(eventName, fn) {
const _this = this;
// 单次监听时改造监听函数,emit时会自动进行事件移除
const _fn = function () {
_this.off(eventName);
fn.apply(null, arguments);
};
this.on(eventName, _fn);
return this;
}
}