Event message broker with Typescript

TLDR;

Event broker to struktura pozwalająca na wymianę informacji pomiędzy nadawcą a odbiorcami, działająca niezalenie od obu aktorów (w przeciwieństwie do wzoraca obserwator).

Jest to wbrew pozorom jedna z prostszych struktur. Jej głównym elementem jest store, który jest niczym innym tylko zbiorem funkcji:

const listeners: { [channel: string]: Function } = {}

Głównymi funkcjami są:

//addListener(channel: string, cb: Function): void
//emit(channel: string, ...props): void

Zacznijmy od prostej wersji addListener():

interface Listener {
  removeListener: () => void
}

function addListener<T extends {}>(channel: string, cb: (props: T)): Listener {
  if (!listeners[channel]) {
    listeners[channel] = cb
  }

  return {
    removeListener: () => {
      delete listeners[channel]
    },
  }
}

Nasza metoda zwraca obiekt z referancją do metody listenera. Dzięki temu w łatwy sposób mozna skasowac listener nie znając danego channelu.

Następna metodą jest emit():

function emit<T extends {}>(channel: string, props: T): void {
  if (listeners[channel]) {
    listeners[channel](props)
  }
}

I tyle, podstawowa wersja EventBusa została zaimplementowana. Porozmawiajmy o benefitach tego rozwiązania. Warstwy callera oraz zdarzenia są kompletnie oddzielone, dzięki temu projektowany system jest bardzo elastyczny, skalowalny.

polski It’s now posible to generate preview images for social networks (Twitter, Slack, LinkedIn…).

twitter card

Event bus

This great idea come from a conversation I had with Luciano Mammino (aka @Loige). I basically took 85% of his code. Thanks Luciano 😊

How to do it?

About the authorPiotr Pietruszka

For the last decade, Maxence Poutord has worked with a variety of web technologies. He is currently focused on front-end development. On his day to day job, he is working as a senior front-end engineer at VSware. He is also an occasional tech speaker and a mentor. As a digital nomad, he is living where the WiFi and sun are 😎
Do you want to know more? Visit my website!