UNPKG

@ayanaware/bento

Version:

Modular runtime framework designed to solve complex tasks

80 lines 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EntityEvents = void 0; const errors_1 = require("@ayanaware/errors"); class EntityEvents { constructor(name, options) { this.subject = new Map(); this.subCount = 0; this.subscriptions = new Map(); this.name = name; this.options = options; // create new emitter this.emitter = this.options.eventEmitter(); // prevent throwing of 'error' events this.emitter.addListener('error', () => { }); } /** * Emit Event * @param name Event name * @param args Event args */ emit(name, ...args) { this.emitter.emit(name, ...args); } /** * Emit Event and store as subject * @param name Event name * @param args Event args */ emitSubject(name, ...args) { this.subject.set(name, args); this.emit(name, ...args); } /** * Purges subject data for event * @param name Event name */ purgeSubject(name) { this.subject.delete(name); } subscribe(name, handler, context) { const id = this.subCount++; // rewrap handler, if context provided if (context) handler = handler.bind(context); // if there is subject data for this event, call now if (this.subject.has(name)) { try { handler.call(context, this.subject.get(name)); } catch (e) { throw new errors_1.ProcessingError(`Failed to call subject handler for "${name}"`).setCause(e); } } // add handler to emitter this.emitter.addListener(name, handler); this.subscriptions.set(id, { name, handler }); return id; } unsubscribe(id) { if (typeof id !== 'undefined') { if (typeof id !== 'number') throw new errors_1.IllegalArgumentError('If given an argument, it must be number'); const subscription = this.subscriptions.get(id); if (!subscription) return; this.emitter.removeListener(subscription.name, subscription.handler); this.subscriptions.delete(id); } else { // called with no id, remove all subscriptions for (const [subId, subscription] of this.subscriptions.entries()) { this.emitter.removeListener(subscription.name, subscription.handler); this.subscriptions.delete(subId); } } } } exports.EntityEvents = EntityEvents; //# sourceMappingURL=EntityEvents.js.map