Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Initialize the bus only if required #587

Merged
merged 1 commit into from Mar 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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') {
skjnldsv marked this conversation as resolved.
Show resolved Hide resolved
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)
}