Skip to content
On this page

函数不能作为索引签名的问题

ts
let map: Map<string, Array<Function>> = new Map()

用 indexOf 读取签名 并且删除不能直接赋值 null

ts
mapget(theme)[cb] = null

在 unsubscribe 方法中,代码 并不能正确地将回调函数从订阅列表中删除。 这是因为 ma.get(theme)[cb] 会将 cb 作为数组的下标来访问数组中的元素,但是 cb 是一个函数,无法直接作为数组下标使用。 以下是一个简单观察者模式的实现

ts
class Broker {
  private subs: Map<string, Function[]> = new Map();

  subscribe(theme: string, cb: Function) {
    if (!this.subs.has(theme)) {
      this.subs.set(theme, []);
    }
    this.subs.get(theme)!.push(cb);
  }

  unsubscribe(theme: string, cb: Function) {
    const callbacks = this.subs.get(theme);
    if (callbacks) {
      const index = callbacks.indexOf(cb);
      if (index !== -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  emit(theme: string) {
    const callbacks = this.subs.get(theme);
    if (callbacks) {
      callbacks.forEach((cb) => {
        cb();
      });
    }
  }
}

const em = new Broker();

const cb = () => {
  console.log("aa");
};

em.subscribe("aa", cb);
em.subscribe("aa", () => {
  console.log("bb");
});

em.emit("aa"); // 输出 "aa" 和 "bb"

em.unsubscribe("aa", cb);

em.emit("aa"); // 只输出 "bb"