简易的事件监听EventBus

Published: · LastMod: June 17, 2023 · 96 words

简易的事件监听 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const createEvent = () => ({
  events: {} as any,
  on(eventName: string, callback: Function) {
    this.events[eventName]?.push(callback) ||
      (this.events[eventName] = [callback]);

    return () => {
      this.events[eventName] = this.events[eventName].filter(
        (e: any) => e !== callback
      );
    };
  },
  emit(eventName: string, ...args: any[]) {
    const callbacks = this.events[eventName];
    callbacks.forEach((callback: Function) => callback(...args));
  },
});

usage 🔗

1
2
3
4
5
6
const events = createEvent();
events.on("say", function () {
  console.log("say hello");
});

events.emit("say");