UNPKG

@inweb/eventemitter2

Version:

JavaScript event emitter

87 lines (86 loc) 3.12 kB
/** * The event interface for {@link IEventEmitter}. */ export interface IEvent { /** * Event type. */ type: string; } /** * Event emitter interface. */ export interface IEventEmitter { /** * Registers a new listener for the event type. * * @param type - The type of event to listen to. * @param listener - The function that gets called when the event is fired. */ addEventListener(type: string, listener: (event: IEvent) => void): this; /** * Removes the listener for the event type. * * @param type - The type of the event that gets removed. * @param listener - The listener function that gets removed. */ removeEventListener(type: string, listener: (event: IEvent) => void): this; /** * If `type` is specified, removes all registered listeners for type, otherwise removes all registered * listeners. * * @param type - The type of the listener that gets removed. */ removeAllListeners(type?: string): this; /** * Fires the event. Calls each of the listeners registered for the event type `event.type`, in the * order they were registered. * * @param event - The event that gets fired. */ emitEvent(event: IEvent): boolean; /** * Registers a new listener for the event type. Alias to {@link addEventListener | addEventListener()} * * @param type - The type of event to listen to. * @param listener - The function that gets called when the event is fired. */ on(type: string, listener: (event: any) => void): this; /** * Removes the listener from an event type. Alias to * {@link removeEventListener | removeEventListener()}. * * @param type - The type of the event that gets removed. * @param listener - The listener function that gets removed. */ off(type: string, listener: (event: any) => void): this; /** * Fires the event. Alias to {@link emitEvent | emitEvent()}. * * @param type - The type of event that gets fired. * @param args - The event properties. */ emit(type: string | object, ...args: any[]): boolean; } /** * The minimal basic event that can be emitted by a {@link EventEmitter2}. */ export interface Event<T extends string = string> extends IEvent { /** * Event type. */ type: T; } /** * Event emitter for custom objects. */ export declare class EventEmitter2<EventMap extends Record<string, any> = Record<string, any>> implements IEventEmitter { private _listeners; addEventListener<T extends keyof EventMap>(type: T, listener: (event: EventMap[T]) => void): this; removeEventListener<T extends keyof EventMap>(type: T, listener: (event: EventMap[T]) => void): this; removeAllListeners<T extends keyof EventMap>(type?: T): this; emitEvent<T extends keyof EventMap>(event: Event<Extract<T, string>> & EventMap[T]): boolean; on(type: string, listener: (event: any) => void): this; off(type: string, listener: (event: any) => void): this; emit(type: string | object, ...args: any[]): boolean; }