1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-10 16:11:13 -05:00
denoland-deno/js/dispatch.ts
2018-07-24 10:38:11 -04:00

29 lines
856 B
TypeScript

// 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);
}
});