兩種模式都是為了實作對象間的一種一對多的依賴關系。
觀察者模式:訂閱者和訂閱目标是聯系在一起的,訂閱者發生變化,逐個通知訂閱目标。
釋出訂閱模式:也是觀察者模式的一種,但釋出訂閱模式中釋出者和訂閱者并不知道彼此的存在,消息不會直接發送給訂閱者,而是由一個消息中心或者叫做排程中心,将過濾後的消息發送給所有的訂閱者。
兩種模式的差別就在于釋出訂閱模式有一個消息中心進行消息的過濾和分發。
/**
* 釋出訂閱者
* 支援事件監聽、移除、單次監聽、監聽事件數量限制
*/
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;
}
}