UNPKG

@iotile/iotile-device

Version:

A typescript library for interfacing with IOTile BLE devices

72 lines 2.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const iotile_common_1 = require("@iotile/iotile-common"); const config_1 = require("../config"); class AbstractNotificationService { } exports.AbstractNotificationService = AbstractNotificationService; class EventManager { constructor(event) { this.callbacks = {}; } addCallback(callback) { let id = iotile_common_1.guid(); this.callbacks[id] = callback; return id; } triggerCallback(event, args) { for (let callback in this.callbacks) { try { this.callbacks[callback](event, args); } catch (err) { config_1.catNotify.error(`Could not trigger notification callback: ${event}`, err); } } } removeAll() { this.callbacks = {}; } removeCallback(handlerId) { if (handlerId in this.callbacks) { delete this.callbacks[handlerId]; } else { throw new iotile_common_1.UnknownKeyError('Unknown event handler key: ' + handlerId); } } } exports.EventManager = EventManager; class BasicNotificationService extends AbstractNotificationService { constructor() { super(); this.events = {}; } subscribe(event, callback) { if (!(event in this.events)) { this.events[event] = new EventManager(event); } let handlerId = this.events[event].addCallback(callback); let that = this; let handler = function () { that.events[event].removeCallback(handlerId); }; return handler; } ; notify(event, args) { if (event in this.events) { let manager = this.events[event]; manager.triggerCallback(event, args); } } ; removeAll() { for (let event in this.events) { this.events[event].removeAll(); } this.events = {}; } } exports.BasicNotificationService = BasicNotificationService; //# sourceMappingURL=notification-service.js.map