const EventBus = { /** * events stored as object with each field being an event */ events: {}, /** * Call all callbacks for given event * @param {string} event name of event * @param {*} data data sent to all event callbacks */ dispatch: (event, data) => { if (!EventBus.events[event]) { return; } EventBus.events[event].forEach(callback => callback(data)); }, /** * @param event - the name of the event * @param callback - the function to be called */ subscribe: (event, callback) => { if (!EventBus.events[event]) { EventBus.events[event] = []; } EventBus.events[event].push(callback); }, /** * Must be called with the exact same callback as subscribe * as we match functions by their .toString() * @param event - the name of the event * @param callback - the function to be removed */ unsubscribe: (event, callback) => { let newEvents = EventBus.events[event].filter((event) => { // hack to ensure we remove the right event if (!(callback.toString() == event.toString())) { return event; } }) EventBus.events[event] = newEvents; } } export default EventBus;