"use strict"; /** * Base class to implement an event system in any class. Events can be dispatched and * subscribed/unsubscribed. Events can have multiple registered callbacks. */ class EventDispatcher { constructor() { this._events = {}; } /** * Dispatch a named event. Calls all callbacks that are subscribed to this event. */ dispatch(eventName, data = null) { if (this._events[eventName]) { this._events[eventName].forEach((callback) => { callback(data); }); } } /** * Subscribe to an event. */ on(eventName, callback) { if (!this._events[eventName]) { this._events[eventName] = []; } this._events[eventName].push(callback); } /** * Unsubscribe from an event. Not sure how to unsubscribe anonymous functions though. * If callback is not found, nothing happens. */ off(eventName, callback) { if (this._events[eventName]) { this._events[eventName] = this._events[eventName].filter(item => item !== callback); } } }