UNPKG

theatre-events

Version:

A full implementation of a standard event dispatcher for javascript

60 lines 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var event_listener_1 = require("./../event-listener"); /** * An asynchronous implementation of an event broadcaster */ var AsynchronousEventBroadcaster = (function () { function AsynchronousEventBroadcaster() { this.subscribers = new Map(); } /** * {@inheritdoc} */ AsynchronousEventBroadcaster.prototype.broadcast = function (payload) { var _this = this; var promises = []; var priorities = []; this.subscribers.forEach(function (s, priority) { return priorities.push(priority); }); priorities.sort().map(function (priority) { _this.subscribers.get(priority).map(function (s) { return promises.push(s(payload)); }); }); return Promise.all(promises).then(function () { return payload; }); }; /** * {@inheritdoc} */ AsynchronousEventBroadcaster.prototype.subscribe = function (subscriber) { subscriber.priority = subscriber.priority || event_listener_1.NORMAL_PRIORITY; if (!this.subscribers.get(subscriber.priority)) { this.subscribers.set(subscriber.priority, []); } this.subscribers.get(subscriber.priority).push(subscriber); }; /** * {@inheritdoc} */ AsynchronousEventBroadcaster.prototype.remove = function (subscriber) { var _this = this; this.subscribers.forEach(function (subscribers, priority) { subscribers.map(function (s, i) { if (s !== subscriber) { return; } subscribers.splice(i, 1); }); if (!subscribers.length) { _this.subscribers.delete(priority); } }); }; /** * {@inheritdoc} */ AsynchronousEventBroadcaster.prototype.clear = function () { this.subscribers = new Map(); }; return AsynchronousEventBroadcaster; }()); exports.default = AsynchronousEventBroadcaster; //# sourceMappingURL=asynchronous-event-broadcaster.js.map