feat: added refs, refactored UINode for more concise build functions

This commit is contained in:
Daniel Ledda
2022-04-02 23:54:51 +02:00
parent fcec98d7e5
commit e77b89ebee
14 changed files with 227 additions and 156 deletions

39
src/Ref.ts Normal file
View File

@@ -0,0 +1,39 @@
export default class Ref<T extends { toString(): string } | string | null = string> {
private watchers: Array<(newVal: T) => void> | null = null;
private value: T;
private asString?: string;
private isString: boolean;
constructor(val: T) {
this.value = val;
this.isString = typeof val === "string";
}
watch(callback: (newVal: T) => void): void {
if (this.watchers === null) {
this.watchers = [];
}
this.watchers.push(callback);
}
get val(): T {
return this.value;
}
set val(val: T) {
this.watchers?.forEach(watcher => watcher(val));
this.value = val;
}
toString(): string {
if (!this.asString) {
if (this.isString) {
return this.val as unknown as string;
} else {
this.asString = this.val?.toString() ?? "null";
}
}
return this.asString;
}
}