觀察者模式與發布訂閱模式是解耦模組間通訊的核心模式。本文從零實現 ObserverList、Subject、PubSub 核心類別,對比兩者差異,並提供生產級事件總線、TypeScript 泛型版本與 Vue/React 整合範例。
class ObserverList {
constructor() { this.list = []; }
add(obj) { return this.list.push(obj); }
remove(obj) {
const idx = this.list.indexOf(obj);
if (idx > -1) this.list.splice(idx, 1);
}
get(index) { return this.list[index]; }
count() { return this.list.length; }
}
class Subject {
constructor() { this.observers = new ObserverList(); }
addObserver(observer) { this.observers.add(observer); }
removeObserver(observer) { this.observers.remove(observer); }
notify(context) {
for (let i = 0; i < this.observers.count(); i++) {
this.observers.get(i).update(context);
}
}
}
// 使用
const subject = new Subject();
const observer1 = { update: (ctx) => console.log('O1:', ctx) };
const observer2 = { update: (ctx) => console.log('O2:', ctx) };
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notify({ event: 'dataChanged', payload: 123 });
// O1: {event: 'dataChanged', payload: 123}
// O2: {event: 'dataChanged', payload: 123}
class PubSub {
constructor() {
this.topics = Object.create(null); // 無原型物體,避免原型污染
this.subUid = -1;
}
// 訂閱:返回 token 用於取消訂閱
subscribe(topic, func) {
if (!this.topics[topic]) this.topics[topic] = [];
const token = `sub_${++this.subUid}_${Date.now()}`;
this.topics[topic].push({ token, func });
return token;
}
// 發布:同步執行所有訂閱者
publish(topic, args) {
const subscribers = this.topics[topic];
if (!subscribers || !subscribers.length) return false;
// 複製陣列防止訂閱者在回呼中修改原陣列
[...subscribers].forEach(({ func }) => {
try { func(topic, args); }
catch (e) { console.error(`PubSub error in ${topic}:`, e); }
});
return true;
}
// 非同步發布 (微任務隊列)
publishAsync(topic, args) {
const subscribers = this.topics[topic];
if (!subscribers?.length) return Promise.resolve(false);
return Promise.all(
[...subscribers].map(({ func }) =>
Promise.resolve().then(() => func(topic, args)).catch(console.error)
)
).then(() => true);
}
// 取消訂閱
unsubscribe(token) {
for (const topic in this.topics) {
const idx = this.topics[topic].findIndex(s => s.token === token);
if (idx > -1) {
this.topics[topic].splice(idx, 1);
if (!this.topics[topic].length) delete this.topics[topic];
return token;
}
}
return false;
}
// 清空主題
clear(topic) {
if (topic) delete this.topics[topic];
else this.topics = Object.create(null);
}
}
// 全域事件總線單例
export const eventBus = new PubSub();
type EventMap = {
'user:login': { userId: string; timestamp: number };
'user:logout': { userId: string };
'cart:update': { items: CartItem[]; total: number };
};
type EventCallback = (data: T) => void;
class TypedEventBus {
private subscribers = new Map}>>();
private idCounter = 0;
subscribe(topic: K, cb: EventCallback): number {
const id = ++this.idCounter;
if (!this.subscribers.has(topic)) this.subscribers.set(topic, new Set());
this.subscribers.get(topic)!.add({ id, cb });
return id;
}
publish(topic: K, data: EventMap[K]): void {
this.subscribers.get(topic)?.forEach(({ cb }) => {
try { cb(data); } catch (e) { console.error(e); }
});
}
unsubscribe(id: number): boolean {
for (const set of this.subscribers.values()) {
for (const sub of set) {
if (sub.id === id) return set.delete(sub);
}
}
return false;
}
}
export const typedBus = new TypedEventBus();
// 使用:完整型別推導
typedBus.subscribe('user:login', ({ userId }) => console.log(`User ${userId} logged in`));
typedBus.publish('user:login', { userId: 'u123', timestamp: Date.now() }); // ✅
// typedBus.publish('user:login', { foo: 'bar' }); // ❌ TypeScript 編譯錯誤
plugin:register,插件訂閱並註冊自身能力。unsubscribe(token)。WeakMap 儲存訂閱關係(Key 為觀察者物件),觀察者被 GC 時自動釋放。掌握觀察者與發布訂閱,能構建鬆耦合、高擴展、易測試的前端架構。