解耦事件的生产者与消费者。

本节要点

  • 观察者模式维护订阅列表
  • 发布订阅通过事件总线解耦
  • 记得取消订阅避免内存泄漏

代码示例

class Emitter {
  constructor() { this.map = new Map(); }
  on(key, fn) {
    if (!this.map.has(key)) this.map.set(key, []);
    this.map.get(key).push(fn);
  }
  emit(key, data) {
    (this.map.get(key) || []).forEach(fn => fn(data));
  }
}
提示:组件销毁时移除监听,避免悬空引用。