Skip to content

useEventBus

Category
Export Size
272 B
Last Changed
5 days ago

A basic event bus

Demo

Usage

tsx
import { 
useEventBus
} from '@reause/core'
const
bus
=
useEventBus
<string>('news')
function
listener
(
event
: string) {
console
.
log
(`news: ${
event
}`)
} // listen to an event const
unsubscribe
=
bus
.
on
(
listener
)
// fire an event
bus
.
emit
('The Tokyo Olympics has begun')
// unregister the listener
unsubscribe
()
// or
bus
.
off
(
listener
)
// clearing all listeners
bus
.
reset
()

React has no scope disposal, so on / once return an unsubscribe function; when a component owns a subscription, unsubscribe from a useEffect cleanup:

tsx
import { 
useEventBus
} from '@reause/core'
import {
useEffect
} from 'react'
function
NewsTicker
() {
const {
on
,
emit
} =
useEventBus
<string>('news')
useEffect
(() =>
on
(
event
=>
console
.
log
(`news: ${
event
}`)), [])
return <
button
type="button" onClick={() =>
emit
('The Tokyo Olympics has begun')}>Broadcast</button>
}

TypeScript

Using EventBusKey is the key to bind the event type to the key, similar to upstream's InjectionKey util.

ts
// fooKey.ts
import type { 
EventBusKey
} from '@reause/core'
export const
fooKey
:
EventBusKey
<{
name
: 'foo' }> =
Symbol
('symbol-key')
tsx
import { 
useEventBus
} from '@reause/core'
import {
fooKey
} from './fooKey'
const
bus
=
useEventBus
(
fooKey
)
bus
.
on
((
e
) => {
// `e` will be `{ name: 'foo' }` })

Type Declarations

ts
export type EventBusListener<T = unknown, P = any> = (event: T, payload?: P) => void

export type EventBusEvents<T, P = any> = Set<EventBusListener<T, P>>

export interface EventBusKey<T> extends Symbol {
}

export type EventBusIdentifier<T = unknown> = EventBusKey<T> | string | number

export interface UseEventBusReturn<T, P> {
    on: (listener: EventBusListener<T, P>) => () => void;
    once: (listener: EventBusListener<T, P>) => () => void;
    emit: (event?: T, payload?: P) => void;
    off: (listener: EventBusListener<T>) => void;
    reset: () => void;
}

export const events

export function useEventBus<T = unknown, P = any>(key: EventBusIdentifier<T>): UseEventBusReturn<T, P>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

No recent changes

Released under the MIT License. v0.1.8