First alpha
This commit is contained in:
46
src/helper/observable.ts
Executable file
46
src/helper/observable.ts
Executable file
@ -0,0 +1,46 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user