2019-01-12 02:33:44 +07:00
|
|
|
import { IDisposable } from "@coder/disposable";
|
|
|
|
|
|
|
|
export interface Event<T> {
|
|
|
|
(listener: (e: T) => void): IDisposable;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-02-06 23:16:43 +07:00
|
|
|
* Emitter typecasts for a single event type.
|
2019-01-12 02:33:44 +07:00
|
|
|
*/
|
|
|
|
export class Emitter<T> {
|
2019-02-06 23:16:43 +07:00
|
|
|
private listeners = <Array<(e: T) => void>>[];
|
2019-01-12 02:33:44 +07:00
|
|
|
|
|
|
|
public get event(): Event<T> {
|
|
|
|
return (cb: (e: T) => void): IDisposable => {
|
|
|
|
if (this.listeners) {
|
|
|
|
this.listeners.push(cb);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
dispose: (): void => {
|
|
|
|
if (this.listeners) {
|
|
|
|
const i = this.listeners.indexOf(cb);
|
|
|
|
if (i !== -1) {
|
|
|
|
this.listeners.splice(i, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-02-06 23:16:43 +07:00
|
|
|
* Emit an event with a value.
|
2019-01-12 02:33:44 +07:00
|
|
|
*/
|
|
|
|
public emit(value: T): void {
|
|
|
|
if (this.listeners) {
|
|
|
|
this.listeners.forEach((t) => t(value));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-02-06 23:16:43 +07:00
|
|
|
* Dispose the current events.
|
2019-01-12 02:33:44 +07:00
|
|
|
*/
|
|
|
|
public dispose(): void {
|
2019-02-06 23:16:43 +07:00
|
|
|
this.listeners = [];
|
2019-01-12 02:33:44 +07:00
|
|
|
}
|
2019-02-06 07:08:48 +07:00
|
|
|
}
|