Skip to content

Commit

Permalink
feat: 🎸 dispatch event when app is exported
Browse files Browse the repository at this point in the history
makes it easier for consumers to listen for a loaded app without using
the lazy-loader explicitly
  • Loading branch information
nutgaard committed Jan 3, 2022
1 parent d185da3 commit 98d7456
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { importer, eksporter } from './navspa';
import { importer, eksporter, exportEvent } from './navspa';
import { importer as importerAsync, importerLazy, preload } from './async/async-navspa';
export { AsyncSpaConfig } from './async/async-navspa';

Expand All @@ -10,7 +10,8 @@ export const AsyncNavspa = {

export const Navspa = {
importer,
eksporter
eksporter,
exportEvent
};

export default Navspa;
3 changes: 3 additions & 0 deletions src/navspa.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as Feilmelding from './feilmelding';
import { createCustomEvent } from './utils';

interface DeprecatedNAVSPAScope {
[name: string]: DeprecatedNAVSPAApp;
Expand All @@ -24,6 +25,7 @@ type NAVSPAApp = {

export const scope: DeprecatedNAVSPAScope = (global as any)['NAVSPA'] = (global as any)['NAVSPA'] || {}; // tslint:disable-line
export const scopeV2: NAVSPAScope = (global as any)['NAVSPA-V2'] = (global as any)['NAVSPA-V2'] || {}; // tslint:disable-line
export const exportEvent: string = 'NAVSPA-eksporter';

export function eksporter<PROPS>(name: string, component: React.ComponentType<PROPS>) {
scope[name] = (element: HTMLElement, props: PROPS) => {
Expand All @@ -37,6 +39,7 @@ export function eksporter<PROPS>(name: string, component: React.ComponentType<PR
ReactDOM.unmountComponentAtNode(element);
}
}
document.dispatchEvent(createCustomEvent(exportEvent, name));
}

export function importer<P>(name: string, config?: NAVSPAAppConfig): React.ComponentType<P> {
Expand Down
10 changes: 10 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export function createCustomEvent<T>(type: string, detail: T): Event {
try {
return new CustomEvent(type, { detail });
} catch (e) {
// IE11 fallback
const event = document.createEvent('CustomEvent');
event.initCustomEvent(type, false, false, detail);
return event;
}
}

0 comments on commit 98d7456

Please sign in to comment.