mapcomplete/UI/UIEventSource.ts

53 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-06-23 22:35:19 +00:00
export class UIEventSource<T>{
public data : T;
private _callbacks = [];
constructor(data: T) {
this.data = data;
}
2020-06-29 01:12:44 +00:00
public addCallback(callback: ((latestData : T) => void)) {
2020-06-23 22:35:19 +00: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 {
for (const callback of this._callbacks) {
callback(this.data);
2020-06-23 22:35:19 +00:00
}
}
2020-07-08 09:23:36 +00:00
public map<J>(f: ((T) => J),
extraSources : UIEventSource<any>[] = []): UIEventSource<J> {
2020-06-23 22:35:19 +00:00
const self = this;
2020-07-08 09:23:36 +00:00
const update = function () {
2020-06-23 22:35:19 +00:00
newSource.setData(f(self.data));
newSource.ping();
2020-07-08 09:23:36 +00:00
}
this.addCallback(update);
for (const extraSource of extraSources) {
extraSource.addCallback(update);
}
const newSource = new UIEventSource<J>(
f(this.data)
);
2020-07-08 09:23:36 +00:00
2020-06-23 22:35:19 +00:00
return newSource;
}
}