Skip to content

Commit

Permalink
fix: Initialize the bus only if required
Browse files Browse the repository at this point in the history
Currently the bus is initialized when the file is imported
and as the bus requires the window to be present it fails for
e.g. testing without a DOM environment.

To fix this the bus is now initialized on the first usage
and while the window is not present only a stub is used.

Signed-off-by: Ferdinand Thiessen <rpm@fthiessen.de>
  • Loading branch information
susnux committed Mar 8, 2023
1 parent 0ab7d2f commit 7fcd3a1
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions lib/index.ts
Expand Up @@ -16,30 +16,44 @@ declare global {
}
}

let bus: EventBus | null = null

function getBus(): EventBus {
if ((typeof window.OC !== 'undefined') && window.OC._eventBus && typeof window._nc_event_bus === 'undefined') {
if (bus !== null) {
return bus
}

if (typeof window === 'undefined') {
// testing or SSR
return new Proxy({} as EventBus, {
get: () => {
return () => console.error('Window not available, EventBus can not be established!')
}
})
}

if (typeof window.OC !== 'undefined' && window.OC._eventBus && typeof window._nc_event_bus === 'undefined') {
console.warn('found old event bus instance at OC._eventBus. Update your version!')
window._nc_event_bus = window.OC._eventBus
}

// Either use an existing event bus instance or create one
if (typeof window._nc_event_bus !== 'undefined') {
return new ProxyBus(window._nc_event_bus)
if (typeof window?._nc_event_bus !== 'undefined') {
bus = new ProxyBus(window._nc_event_bus)
} else {
return window._nc_event_bus = new SimpleBus()
bus = window._nc_event_bus = new SimpleBus()
}
return bus
}

const bus = getBus()

/**
* Register an event listener
*
* @param name name of the event
* @param handler callback invoked for every matching event emitted on the bus
*/
export function subscribe(name: string, handler: (string) => void): void {
bus.subscribe(name, handler)
getBus().subscribe(name, handler)
}

/**
Expand All @@ -51,7 +65,7 @@ export function subscribe(name: string, handler: (string) => void): void {
* @param handler callback passed to `subscribed`
*/
export function unsubscribe(name: string, handler: (string) => void): void {
bus.unsubscribe(name, handler)
getBus().unsubscribe(name, handler)
}

/**
Expand All @@ -61,5 +75,5 @@ export function unsubscribe(name: string, handler: (string) => void): void {
* @param event event payload
*/
export function emit(name: string, event: object): void {
bus.emit(name, event)
getBus().emit(name, event)
}

0 comments on commit 7fcd3a1

Please sign in to comment.