OSSecureFileWrapper/src/observable.ts

38 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-12-23 14:18:30 +00:00
export type ObserverCallback<T> = (data: T) => void;
export default class Observable<T = any> {
private subscriber: ObserverCallback<T[]>[] = [];
private events: T[] = [];
private timeout = undefined;
constructor(private collect: boolean = true, private collect_intervall: number = 100) { }
getPublicApi() {
return {
subscribe: (callback: ObserverCallback<T[]>) => {
if (this.subscriber.indexOf(callback) < 0)
this.subscriber.push(callback)
},
unsubscribe: (callback: ObserverCallback<T[]>) => {
let idx = this.subscriber.indexOf(callback);
if (idx >= 0) {
this.subscriber.splice(idx, 1);
}
}
}
}
send(data: T) {
if (!this.collect)
this.subscriber.forEach(e => e([data]));
else {
this.events.push(data);
if (!this.timeout) {
this.timeout = setTimeout(() => {
this.subscriber.forEach(e => e(this.events));
this.timeout = 0;
}, this.collect_intervall);
}
}
}
}