[Partten] PubSub partten

发布时间 2023-10-04 02:22:41作者: Zhentiw

PubSub is one of the most foundational patterns for reactivity. Firing an event out with publish() allows anyone to listen to that event subscribe() and do whatever they want in a decoupled from whatever fires that event.

type AnyFunction = (...args: any[]) => void

const pubSub = {
  events: {} as Record<PropertyKey, AnyFunction[]>,
  subscribe(eventName: string, callback: AnyFunction) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(callback);
  },
  publish(eventName: string, data: any) {
    if (this.events[eventName]) {
      this.events[eventName].forEach((callback) => callback(data));
    }
  }
};

pubSub.subscribe("update", (data) => console.log(data));
pubSub.publish("update", "Update payload");

 

This is a simplest way to fulfill basic reactitivy partten.

Note the publisher has no idea of what is listening to it, so there is no way to unsubscribe or clean up after itself with this simple implementation.