code-server/src/common/emitter.ts

43 lines
778 B
TypeScript
Raw Normal View History

import { Callback } from "./types"
2020-02-04 19:27:46 +00:00
export interface Disposable {
dispose(): void
}
export interface Event<T> {
(listener: Callback<T>): Disposable
2020-02-04 19:27:46 +00:00
}
/**
* Emitter typecasts for a single event type.
*/
export class Emitter<T> {
private listeners: Array<Callback<T>> = []
2020-02-04 19:27:46 +00:00
public get event(): Event<T> {
return (cb: Callback<T>): Disposable => {
2020-02-04 19:27:46 +00:00
this.listeners.push(cb)
return {
dispose: (): void => {
const i = this.listeners.indexOf(cb)
if (i !== -1) {
this.listeners.splice(i, 1)
}
},
}
}
}
/**
* Emit an event with a value.
*/
public emit(value: T): void {
this.listeners.forEach((cb) => cb(value))
}
public dispose(): void {
this.listeners = []
}
}