Skip to content

Commit

Permalink
Merge pull request #43 from navikt/fix/global
Browse files Browse the repository at this point in the history
fix: 🐛 avoid using global
  • Loading branch information
nutgaard authored Mar 28, 2022
2 parents b048f24 + fb8af65 commit d4592bf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/navspa.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as Feilmelding from './feilmelding';
import { createCustomEvent } from './utils';
import { createCustomEvent, getGlobal } from './utils';

interface DeprecatedNAVSPAScope {
[name: string]: DeprecatedNAVSPAApp;
Expand All @@ -23,8 +23,9 @@ type NAVSPAApp = {
unmount(element: HTMLElement): void;
}

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
const globalScope = getGlobal();
export const scope: DeprecatedNAVSPAScope = globalScope['NAVSPA'] = globalScope['NAVSPA'] || {};
export const scopeV2: NAVSPAScope = globalScope['NAVSPA-V2'] = globalScope['NAVSPA-V2'] || {};
export const exportEvent: string = 'NAVSPA-eksporter';

export function eksporter<PROPS>(name: string, component: React.ComponentType<PROPS>) {
Expand Down
12 changes: 12 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* istanbul ignore file */
export function createCustomEvent<T>(type: string, detail: T): Event {
try {
return new CustomEvent(type, { detail });
Expand All @@ -7,4 +8,15 @@ export function createCustomEvent<T>(type: string, detail: T): Event {
event.initCustomEvent(type, false, false, detail);
return event;
}
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
export function getGlobal(): { 'NAVSPA': {}, 'NAVSPA-V2': {} } {
if (typeof globalThis !== 'undefined') return globalThis as any;

// IE11 fallback
if (typeof self !== 'undefined') return self as any;
if (typeof window !== 'undefined') return window as any;
if (typeof global !== 'undefined') return global as any;
throw new Error('Unable to locate globale object');
}

0 comments on commit d4592bf

Please sign in to comment.