UNPKG

@nent/core

Version:

Functional elements to add routing, data-binding, dynamic HTML, declarative actions, audio, video, and so much more. Supercharge static HTML files into web apps without script or builds.

58 lines (57 loc) 2.29 kB
/*! * NENT 2022 */ import { commonState, debugIf, kebabToCamelCase, } from '../../../services/common'; import { getAppProvider, setAppProvider } from './factory'; import { APP_COMMANDS, APP_TOPIC } from './interfaces'; import { DefaultAppProvider } from './providers/default'; /* It listens for actions on the `APP_TOPIC` topic, and then calls the appropriate function on the `AppProvider` that is registered for the current document */ export class AppActionListener { /** * > This function is called by the `AppManager` to initialize the `AppProvider` with the `Window` * object, the `actionBus` and the `eventBus` * @param {Window} win - Window - the window object * @param {IEventEmitter} actionBus - This is the event bus that the app will use to listen for * actions. * @param {IEventEmitter} eventBus - This is the event bus that the app will use to communicate with * the rest of the application. */ initialize(win, actionBus, eventBus) { this.eventBus = eventBus; this.actionsSubscription = actionBus.on(APP_TOPIC, e => { this.handleAction(e); }); this.defaultProvider = new DefaultAppProvider(win, eventBus); } handleAction(actionEvent) { debugIf(commonState.debug, `document-listener: action received ${JSON.stringify(actionEvent)}`); if (actionEvent.command === APP_COMMANDS.RegisterProvider) { const { name = 'unknown', provider } = actionEvent.data; if (provider) { setAppProvider(name, provider); } } else { const currentProvider = getAppProvider(); const commandFuncKey = kebabToCamelCase(actionEvent.command); // Use the registered provider unless it doesn't implement this command let commandFunc = currentProvider ? currentProvider[commandFuncKey] : null; if (!commandFunc) commandFunc = this.defaultProvider[commandFuncKey]; if (commandFunc && typeof commandFunc === 'function') { commandFunc.call(this.defaultProvider, actionEvent.data); } } } /** * It unsubscribes from the actions subscription and destroys the default provider. */ destroy() { var _a; this.actionsSubscription(); (_a = this.defaultProvider) === null || _a === void 0 ? void 0 : _a.destroy(); } }