summaryrefslogtreecommitdiff
path: root/js/dispatch.ts
blob: eeb00f38ef4bf62014b18e2d7b3c77618a3055a6 (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
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
import { typedArrayToArrayBuffer } from "./util";
import { deno as fbs } from "./msg_generated";

export type MessageCallback = (msg: Uint8Array) => void;
//type MessageStructCallback = (msg: pb.IMsg) => void;

const channels = new Map<string, MessageCallback[]>();

export function sub(channel: string, cb: MessageCallback): void {
  let subscribers = channels.get(channel);
  if (!subscribers) {
    subscribers = [];
    channels.set(channel, subscribers);
  }
  subscribers.push(cb);
}

deno.recv((channel: string, ab: ArrayBuffer) => {
  const subscribers = channels.get(channel);
  if (subscribers == null) {
    throw Error(`No subscribers for channel "${channel}".`);
  }

  const ui8 = new Uint8Array(ab);
  for (const subscriber of subscribers) {
    subscriber(ui8);
  }
});