Improve dispoable listener functions

This commit is contained in:
Daniel Imms
2018-01-14 13:18:00 -08:00
parent 70489e5035
commit 85c02f10bf
4 changed files with 65 additions and 27 deletions
+20 -1
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { IEventEmitter, IListenerType } from './Interfaces';
import { IEventEmitter, IListenerType, IDisposable } from './Interfaces';
export class EventEmitter implements IEventEmitter {
private _events: {[type: string]: IListenerType[]};
@@ -19,6 +19,25 @@ export class EventEmitter implements IEventEmitter {
this._events[type].push(listener);
}
/**
* Adds a disposabe listener to the EventEmitter, returning the disposable.
* @param type The event type.
* @param handler The handler for the listener.
*/
public addDisposableListener(type: string, handler: IListenerType): IDisposable {
this.on(type, handler);
return {
dispose: () => {
if (!handler) {
// Already disposed
return;
}
this.off(type, handler);
handler = null;
}
};
}
public off(type: string, listener: IListenerType): void {
if (!this._events[type]) {
return;