Skip to content

@jakguru/vueprint / @jakguru/vueprint/services/bus / BusService

Class: BusService

@jakguru/vueprint/services/bus.BusService

The bus service is a service which allows event-based communication between components, tabs and services. It offers an API similar to the NodeJS EventEmitter class.

Remarks

Accessing the Bus Service

The Bus Service is both injectable and accessible from the global Vue instance:

vue

<script lang="ts">
import { defineComponent, inject } from 'vue'
import type { BusService } from '@jakguru/vueprint'
export default defineComponent({
    setup() {
        const bus = inject<BusService>('bus')
        return {}
    }
    mounted() {
        const bus: BusService = this.config.globalProperties.$bus
    }
})
</script>

Using the Bus Service

Triggering an Event

To trigger an event, simply use the BusService.emit method, where the first argument is the event that you are triggering, the second argument are the BusEventListenOptions used to determine where an event is triggered to, and the remaining arguments are the arguments which will be passed to the listening callbacks.

typescript
bus.emit(
    'some-custom-event',
    { crossTab: true, local: true },
    customArg1,
    customArg2
)

Listening to an Event

To listen to an event, you can use the BusService.on and BusService.once methods, where the first argument is the event that you are listening to, the second argument is the callback which will be triggered when the event occurs, and the last argument is the BusEventListenOptions used to determine the scope of events to subscribe to.

typescript
const someEventCallback = (arg1, arg2, from) => {
    // do something here
}

bus.on(
    'some-custom-event',
    someEventCallback,
    { crossTab: true, local: true }
)

To remove a callback from the listen of callbacks triggered when an event occurs, you can use BusService.off, where the first argument is the event that you want to stop listening to, the second argument is the callback which should stop being triggered, and the last argument are the BusEventListenOptions used to determine the scope of events to unsubscribe from.

Using Custom Events

In order to use custom events in typescript, you will need to add some Typescript Augmentations. For more information, see Typescript Augmentations

Determining if we are currently in the main tab

To determine if the current tab is the main tab, the BusService.isMain method can be used.

Cross-Tab Requests

It is now possible to make requests to other tabs and await their responses. This is done using the BusService.crossTabRequest and BusService.addRequestHandler methods.

Constructors

constructor

new BusService(namespace?): BusService

Create a new bus

Parameters

NameTypeDescription
namespace?stringThe namespace for the BroadcastChannel

Returns

BusService

Defined in

src/services/bus.ts:404

Accessors

active

get active(): ComputedRef<boolean>

Whether the tab is active

Returns

ComputedRef<boolean>

Defined in

src/services/bus.ts:517


inactiveTooLong

get inactiveTooLong(): ComputedRef<boolean>

Whether the tab has been inactive for too long and should have reduced functionality to save user resources

Returns

ComputedRef<boolean>

Defined in

src/services/bus.ts:525


uuid

get uuid(): string

The UUID of the tab

Returns

string

Defined in

src/services/bus.ts:510

Methods

addRequestHandler

addRequestHandler(method, handler): void

Add a function which will handle requests for a method called by BusService.crossTabRequest

Parameters

NameTypeDescription
methodstringThe method which the handler will handle requests for
handler(payload: any) => unknownThe function which will handle requests and return results

Returns

void

Defined in

src/services/bus.ts:750


await

await<K>(event, options?, ...args): Promise<void | (void | void[])[]>

Trigger an event and await for all listeners to process it

Type parameters

NameType
Kextends keyof BusEventCallbackSignatures

Parameters

NameTypeDescription
eventKThe name of the event to await listener processing for
optionsBusEventListenOptions-
...argsParameters<BusEventCallback<K>>The arguments to pass to the event

Returns

Promise<void | (void | void[])[]>

A promise that resolves when all listeners have processed the event

Remarks

This method is especially useful within service workers where you may need to use event.waitUntil to ensure that all listeners have processed the event before the service worker is terminated

Defined in

src/services/bus.ts:659


crossTabRequest

crossTabRequest<ResponseType>(method, payload, targets?, timeout?): Promise<Map<string, undefined | ResponseType>>

Make a request to all tabs and await their responses

Type parameters

NameType
ResponseTypeextends unknown = any

Parameters

NameTypeDefault valueDescription
methodstringundefinedThe method to call
payloadanyundefinedThe payload to send to the method being called
targetsstring[] | "*"'*'The uuids of the tabs to send the request to. Accepts "*" for all tabs
timeoutnumber500The amount of time to wait for a response

Returns

Promise<Map<string, undefined | ResponseType>>

A map of responses from the tabs

Defined in

src/services/bus.ts:712


emit

emit<K>(event, options?, ...args): void

Trigger an event

Type parameters

NameType
Kextends keyof BusEventCallbackSignatures

Parameters

NameTypeDescription
eventKThe name of the event to emit
optionsBusEventListenOptionsThe options for emitting the event
...argsParameters<BusEventCallback<K>>The arguments to pass to the event

Returns

void

Defined in

src/services/bus.ts:633


getActiveTabs

getActiveTabs(wait?): Promise<string[]>

Get the active tabs

Parameters

NameTypeDefault valueDescription
waitnumber500The time to wait before returning the active tabs

Returns

Promise<string[]>

The active tabs

Defined in

src/services/bus.ts:763


isMain

isMain(wait?): Promise<boolean>

Check if the tab is the main tab

Parameters

NameTypeDefault valueDescription
waitnumber500The time to wait before returning the active tabs

Returns

Promise<boolean>

Whether the tab is the main tab

Defined in

src/services/bus.ts:792


off

off<K>(event, callback, options?): void

Stop listening to an event

Type parameters

NameType
Kextends keyof BusEventCallbackSignatures

Parameters

NameTypeDescription
eventKThe event to stop listening to
callbackBusEventCallback<K>The callback to remove from the event
optionsBusEventListenOptionsThe options for stopping listening to the event

Returns

void

Defined in

src/services/bus.ts:577


on

on<K>(event, callback, options?): void

Listen to an event

Type parameters

NameType
Kextends keyof BusEventCallbackSignatures

Parameters

NameTypeDescription
eventKThe event to listen to
callbackBusEventCallback<K>The callback to call when the event is emitted
optionsBusEventListenOptionsThe options for listening to the event

Returns

void

Defined in

src/services/bus.ts:540


once

once<K>(event, callback, options?): void

Listen to an event once

Type parameters

NameType
Kextends keyof BusEventCallbackSignatures

Parameters

NameTypeDescription
eventKThe event to listen to
callbackBusEventCallback<K>The callback to call when the event is emitted
optionsBusEventListenOptionsThe options for listening to the event

Returns

void

Defined in

src/services/bus.ts:596

Vueprint is a commercial work product released under the MIT License and is provided as-is with no warranty or guarantee of support.