summaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/lib/broadcast/mapChannel.ts
blob: efd76eb8ca692aa60c600d536d63faeed9614e04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const channel: BroadcastChannel = new BroadcastChannel("odlux_map");
const listeners: { [key: string]: ((data: any) => void)[] } = {};

channel.onmessage = (eventMessage: MessageEvent<any>) => {
  const { key, data } = eventMessage.data;
  if (listeners[key]) {
    listeners[key].forEach(listener => listener(data));
  }
};

export const sendMapMessage = (data: any, key: string) => {
  channel.postMessage({ key, data });
};

export const addMapMessageListener = (key: string, listener: (data: any) => void) => {
  if (!listeners[key]) {
    listeners[key] = [];
  }
  
  if (!listeners[key].find(l => l === listener)) {
    listeners[key].push(listener);
  }

  return () => {
    listeners[key] = listeners[key].filter(l => l !== listener);
  }
};