Skip to content

Commit

Permalink
Merge pull request #2517 from revanthmahesh/dispose-eventemitters
Browse files Browse the repository at this point in the history
Support disposing of EventEmitters
  • Loading branch information
Tyriar authored Oct 27, 2019
2 parents edc0957 + f3bbcb3 commit 719fa55
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/common/EventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,26 @@ export interface IEvent<T> {
export interface IEventEmitter<T> {
event: IEvent<T>;
fire(data: T): void;
dispose(): void;
}

export class EventEmitter<T> implements IEventEmitter<T> {
private _listeners: IListener<T>[] = [];
private _event?: IEvent<T>;
private _disposed: boolean = false;

public get event(): IEvent<T> {
if (!this._event) {
this._event = (listener: (e: T) => any) => {
this._listeners.push(listener);
const disposable = {
dispose: () => {
for (let i = 0; i < this._listeners.length; i++) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
return;
if (!this._disposed) {
for (let i = 0; i < this._listeners.length; i++) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
return;
}
}
}
}
Expand All @@ -51,4 +55,11 @@ export class EventEmitter<T> implements IEventEmitter<T> {
queue[i].call(undefined, data);
}
}

public dispose(): void {
if (this._listeners) {
this._listeners.length = 0;
}
this._disposed = true;
}
}

0 comments on commit 719fa55

Please sign in to comment.