Skip to content

Commit

Permalink
feat: add EmitterLike interface
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Dec 18, 2023
1 parent b8a957b commit 28c57cd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ import type {
ListenerMethod,
AllowedEventTypes,
ListenerClassWithHandleMethod,
EmitterLike,
} from './types.js'

/**
* Event emitter is built on top of emittery with support class based
* events and listeners
*/
export class Emitter<EventsList extends Record<string | symbol | number, any>> {
export class Emitter<EventsList extends Record<string | symbol | number, any>>
implements EmitterLike<EventsList>
{
/**
* Event classes to symbols mapping. We need symbols as emittery
* does not support class based event names
Expand Down
34 changes: 34 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,37 @@ export type Listener<Data, ListenerClass extends Constructor> =
| ListenerFn<Data>
| string
| [LazyImport<ListenerClass> | ListenerClass, GetListenersMethods<ListenerClass, Data>?]

/**
* The EmitterLike interface exposes a less strict API to accept
* emitter as an argument to emit events.
*/
export interface EmitterLike<EventsList extends Record<string | symbol | number, any>> {
/**
* Emit event. The event listeners will be called asynchronously
* in parallel.
*
* You can await this method to wait for events listeners to finish
*/
emit<Event extends Constructor<any>>(event: Event, data: InstanceType<Event>): Promise<void>
emit<Name extends keyof EventsList>(event: Name, data: EventsList[Name]): Promise<void>

/**
* Emit events serially. The event listeners will be called asynchronously
* in the same sequence as they are registered.
*
* You can await this method to wait for events listeners to finish
*/
emitSerial<Event extends Constructor<any>>(event: Event, data: InstanceType<Event>): Promise<void>
emitSerial<Name extends keyof EventsList>(event: Name, data: EventsList[Name]): Promise<void>

/**
* Find if an event has one or more listeners
*/
listenerCount(event?: keyof EventsList | Constructor<any>): number

/**
* Get count of listeners for a given event or all the events
*/
hasListeners(event?: keyof EventsList | Constructor<any>): boolean
}

0 comments on commit 28c57cd

Please sign in to comment.