|
@@ -2,15 +2,16 @@ import { cloneDeep } from 'lodash'
|
|
|
import { useEffect, useRef } from 'react'
|
|
|
type SubscriptionParams<T = any> = {
|
|
|
params: T
|
|
|
- event: string | number
|
|
|
+ event: EventType
|
|
|
}
|
|
|
+export type EventType = string | symbol
|
|
|
type Subscription<T> = ({ params, event }: SubscriptionParams<T>) => void
|
|
|
class EventEmitter<T> {
|
|
|
- private subscriptions = new Map<string | number, Subscription<T>>()
|
|
|
+ private subscriptions = new Map<EventType, Subscription<T>>()
|
|
|
constructor() {
|
|
|
this.clear()
|
|
|
}
|
|
|
- useSubscription = (event: string, listener?: Subscription<T>) => {
|
|
|
+ useSubscription = (event: EventType, listener?: Subscription<T>) => {
|
|
|
const callbackRef = useRef<Subscription<T>>()
|
|
|
useEffect(() => {
|
|
|
callbackRef.current = listener
|
|
@@ -25,21 +26,20 @@ class EventEmitter<T> {
|
|
|
}
|
|
|
}, [])
|
|
|
}
|
|
|
- emit = (event: string | number, ...args: T extends any[] ? any[] : any) => {
|
|
|
- if (typeof event === 'string' || typeof event === 'number') {
|
|
|
+ emit = (event: EventType, ...args: T extends any[] ? any[] : any) => {
|
|
|
+ if (typeof event === 'string' || typeof event === 'symbol') {
|
|
|
const subscriptionValuesCallback = this.subscriptions.get(event)
|
|
|
subscriptionValuesCallback?.({
|
|
|
params: cloneDeep(args) as any,
|
|
|
event
|
|
|
})
|
|
|
- } else throw new TypeError('event must be string or number !')
|
|
|
+ } else throw new TypeError('event must be string or symbol !')
|
|
|
}
|
|
|
- removeListener = (event: string) => {
|
|
|
+ removeListener = (event: EventType) => {
|
|
|
this.subscriptions.delete(event)
|
|
|
}
|
|
|
clear = () => {
|
|
|
this.subscriptions.clear()
|
|
|
}
|
|
|
}
|
|
|
-const eventEmitterOverall = new EventEmitter()
|
|
|
-export { EventEmitter, eventEmitterOverall }
|
|
|
+export { EventEmitter }
|