2020-06-24 00:35:19 +02:00
|
|
|
export class UIEventSource<T>{
|
|
|
|
|
|
|
|
public data : T;
|
|
|
|
private _callbacks = [];
|
|
|
|
|
|
|
|
constructor(data: T) {
|
|
|
|
this.data = data;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-06-29 03:12:44 +02:00
|
|
|
public addCallback(callback: ((latestData : T) => void)) {
|
2020-06-24 00:35:19 +02:00
|
|
|
this._callbacks.push(callback);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public setData(t: T): void {
|
|
|
|
if (this.data === t) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.data = t;
|
|
|
|
this.ping();
|
|
|
|
}
|
|
|
|
|
|
|
|
public ping(): void {
|
2020-07-01 17:38:48 +02:00
|
|
|
for (const callback of this._callbacks) {
|
|
|
|
callback(this.data);
|
2020-06-24 00:35:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public map<J>(f: ((T) => J)): UIEventSource<J> {
|
|
|
|
const self = this;
|
|
|
|
this.addCallback(function () {
|
|
|
|
newSource.setData(f(self.data));
|
2020-06-27 03:06:51 +02:00
|
|
|
newSource.ping();
|
2020-06-24 00:35:19 +02:00
|
|
|
});
|
2020-06-27 03:06:51 +02:00
|
|
|
const newSource = new UIEventSource<J>(
|
|
|
|
f(this.data)
|
|
|
|
);
|
2020-06-24 00:35:19 +02:00
|
|
|
|
|
|
|
return newSource;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|