46 lines
1.5 KiB
TypeScript
Executable File
46 lines
1.5 KiB
TypeScript
Executable File
export type ObserverCallback<T> = (data: T[]) => void;
|
|
|
|
export default class Observable<T = any> {
|
|
private subscriber: { callback: ObserverCallback<T>, one: boolean }[] = [];
|
|
private events: T[] = [];
|
|
private timeout = undefined;
|
|
|
|
constructor(private collect: boolean = true, private collect_intervall: number = 100) { }
|
|
|
|
getPublicApi() {
|
|
return {
|
|
subscribe: (callback: ObserverCallback<T>, one: boolean = false) => {
|
|
let oldcb = this.subscriber.find(e => e.callback === callback);
|
|
if (oldcb)
|
|
oldcb.one = one
|
|
else
|
|
this.subscriber.push({ callback, one })
|
|
},
|
|
unsubscribe: (callback: ObserverCallback<T>) => {
|
|
let idx = this.subscriber.findIndex(e => e.callback === callback);
|
|
if (idx >= 0) {
|
|
this.subscriber.splice(idx, 1);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
send(data: T) {
|
|
if (!this.collect)
|
|
this.subscriber.forEach(e => e.callback([data]));
|
|
else {
|
|
this.events.push(data);
|
|
if (!this.timeout) {
|
|
this.timeout = setTimeout(() => {
|
|
this.subscriber.forEach(cb => {
|
|
if (cb.one)
|
|
this.events.forEach(e => cb.callback([e]));
|
|
else
|
|
cb.callback(this.events)
|
|
});
|
|
this.timeout = 0;
|
|
}, this.collect_intervall);
|
|
}
|
|
}
|
|
}
|
|
} |