import { Callback, CallbackId } from "./types"; export class CallbacksManager { protected currentCallbackId = 0; protected callbacks: { [index: number]: { source: Callback; callback: Callback } } = {}; createLinkToCallback = (id: CallbackId) => { const callbackItem = this.callbacks[id]; if (!callbackItem) { throw new Error("Not found callback with id " + id); } this.currentCallbackId++; this.callbacks[this.currentCallbackId] = { source: callbackItem.callback, callback: callbackItem.callback }; return this.currentCallbackId; }; addCallback = (callback: Callback): [number, (value: any) => any] => { this.currentCallbackId++; const realCallback = ((callbackId: CallbackId) => (value: any) => { if (!this.callbacks[callbackId]) { return; } return this.callbacks[callbackId].source(value); })(this.currentCallbackId); this.callbacks[this.currentCallbackId] = { source: callback, callback }; return [this.currentCallbackId, realCallback]; }; changeCallback = (id: CallbackId, callback: Callback) => { if (!this.callbacks[id]) { throw new Error("Not found callback with id " + id); } this.callbacks[id].source = callback; }; getCallback = (id: CallbackId) => { if (!this.callbacks[id]) { throw new Error("Not found callback with id " + id); } return this.callbacks[id].callback; }; releaseCallback = (id: CallbackId) => { delete this.callbacks[id]; }; }