typed-event-emitter
Version:
Alternative event emitter for JavaScript and TypeScript.
75 lines (74 loc) • 3.5 kB
TypeScript
/******************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2016 Simon "Tenry" Burchert *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* EALINGS IN THE SOFTWARE. *
******************************************************************************/
/**
* Generic for callback function with any arguments.
*/
declare type EventHandler<Args extends any[]> = (...args: Args) => void;
/**
* Generic for function that accepts EventHandler (callback) and returns a new
* instance of Listener.
*/
declare type EventBinder<Args extends any[]> = (event: EventHandler<Args>) => Listener;
export declare class EventEmitter {
private eventListeners;
constructor();
addListener<Args extends any[]>(event: EventBinder<Args>, callback: EventHandler<Args>): Listener;
/**
* Alias for `addListener`.
*/
on<Args extends any[]>(event: EventBinder<Args>, callback: EventHandler<Args>): Listener;
/**
* Remove all listeners.
*/
removeListener(): void;
/**
* Remove specific listener.
*
* @param listener Listener to remove.
*/
removeListener(listener: Listener): void;
/**
* Remove callback function from given event.
*
* @param event Event where function might have been added to
* @param callback Callback function to remove from event
*/
removeListener(event: Function, callback?: Function): void;
/**
* Emit event. Calls all bound listeners with args.
*/
protected emit<Args extends any[]>(event: EventBinder<Args>, ...args: Args): void;
/**
* @typeparam T The event handler signature.
*/
registerEvent<T extends any[]>(): (handler: EventHandler<T>) => Listener;
}
export declare class Listener {
owner: EventEmitter;
event: Function;
callback: Function;
constructor(owner: EventEmitter, event: Function, callback: Function);
unbind(): void;
}
export {};