UNPKG

dbl-utils

Version:

Utilities for dbl, adba and others projects

82 lines (81 loc) 2.71 kB
type EventCallback = (...data: any[]) => any | Function; /** * Class EventHandler to manage event subscriptions and dispatching. * * @example * ```ts * const handler = new EventHandler(); * handler.subscribe('say', msg => console.log(msg), 'id1'); * handler.dispatch('say', 'hello'); * ``` */ export declare class EventHandler { private events; private patterns; private cache; /** * Construct an instance of EventHandler. */ constructor(); /** * Converts a wildcard string to a regular expression. * @param wildcardString - The wildcard string to convert. * @returns A RegExp object. */ private wildcardToRegExp; /** * Escapes special characters in a string for use in a regular expression. * @param string - The string to escape. * @return The escaped string. */ private escapeRegExp; /** * Dispatches an event to all subscribed callbacks. * @param event - The event name to dispatch. * @param data - Data to be passed to the callback function. * @returns A promise resolved with an array of callback responses. * * @example * ```ts * await handler.dispatch('say', 'hi'); * ``` */ dispatch(event: string, ...data: any[]): Promise<any[]>; /** * Subscribes to an event or a pattern of events. * @param eventString - The event name or pattern to subscribe to. * @param callback - The callback function to execute when the event is dispatched. * @param id - An identifier for the subscription, used for unsubscribing. * * @example * ```ts * handler.subscribe('user.*', cb, 'id'); * ``` */ subscribe(eventString: string, callback: EventCallback, id: string): void; /** * Unsubscribes from an event or pattern of events. * @param eventString - The event name or pattern to unsubscribe from. * @param id - The identifier of the subscription to remove. * * @example * ```ts * handler.unsubscribe('user.*', 'id'); * ``` */ unsubscribe(eventString: string, id: string): void; /** * Remove an event or pattern from the cache based on id. * @param event - The event name or pattern. * @param id - The identifier of the subscription to remove from the cache. */ private updateCache; /** * Update cache by removing pattern-matching events based on id. * @param regex - The regular expression pattern to match against. * @param id - The identifier for the subscription to be removed from the cache. */ private updateCacheWithPattern; } declare const _default: EventHandler; export default _default;