UNPKG

tlojs

Version:

The Last One - The last npm package you'll need to install

93 lines (92 loc) 2.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseEvent = exports.GlobalEventHub = exports.EventHub = void 0; var EventHub = /** @class */ (function () { function EventHub() { this.registered = {}; } /** * Dispatches a an event to any listeners. If no listeners exist, the event will be ignored * @param event EventBase */ EventHub.prototype.dispatch = function (event) { var callbacks = this.registered[event.name]; if (callbacks) { for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i]; try { callback(event); } catch (ex) { console.error("Unable to dispatch " + event.name + " because " + ex, ex); } } } }; /** * Register a callback to an event type * @param eventType * @param callback * @returns */ EventHub.prototype.register = function (eventType, callback) { var instance = new eventType(); var name = instance.name; if (!this.registered[name]) { this.registered[name] = []; } this.registered[name].push(callback); return new EventRegistration(eventType, callback, this); }; /** * Unregister a callback from an event type * @param eventType * @param callback * @returns */ EventHub.prototype.unregister = function (eventType, callback) { var instance = new eventType(); var name = instance.name; if (!this.registered[name]) { return; } var foundIndex = this.registered[name].indexOf(callback); if (foundIndex > -1) { this.registered[name].splice(foundIndex, 1); } }; return EventHub; }()); exports.EventHub = EventHub; /** * The global event hub */ exports.GlobalEventHub = new EventHub(); var BaseEvent = /** @class */ (function () { function BaseEvent(data) { this.data = data; this.globalHub = exports.GlobalEventHub; } /** * Any inherited class can easily dispatch to the global event hub */ BaseEvent.prototype.dispatch = function () { this.globalHub.dispatch(this); }; return BaseEvent; }()); exports.BaseEvent = BaseEvent; var EventRegistration = /** @class */ (function () { function EventRegistration(eventType, callback, eventHub) { this.eventType = eventType; this.callback = callback; this.eventHub = eventHub; } /** * Easy shortcut to unregister an event */ EventRegistration.prototype.unsubscribe = function () { this.eventHub.unregister(this.eventType, this.callback); }; return EventRegistration; }());