Add fallback option to forwarded state

This commit is contained in:
Talia 2023-12-23 17:31:45 +01:00
parent cebd867bd2
commit e38d556531
Signed by: darkwiiplayer
GPG key ID: 7808674088232B3E

View file

@ -85,8 +85,8 @@ export class State extends EventTarget {
} }
} }
forward(property="value") { forward(property="value", fallback) {
return new ForwardState(this, property) return new ForwardState(this, property, fallback)
} }
set(prop, value) { set(prop, value) {
@ -101,11 +101,13 @@ export class State extends EventTarget {
export class ForwardState extends EventTarget { export class ForwardState extends EventTarget {
#backend #backend
#property #property
#fallback
constructor(backend, property) { constructor(backend, property, fallback) {
super() super()
this.#backend = backend this.#backend = backend
this.#property = property this.#property = property
this.#fallback = fallback
const ref = new WeakRef(this) const ref = new WeakRef(this)
const abortController = new AbortController() const abortController = new AbortController()
backend.addEventListener("change", event => { backend.addEventListener("change", event => {
@ -120,7 +122,7 @@ export class ForwardState extends EventTarget {
}, {signal: abortController.signal}) }, {signal: abortController.signal})
} }
get value() { return this.#backend.proxy[this.#property] } get value() { return this.#backend.proxy[this.#property] ?? this.#fallback }
set value(value) { this.#backend.proxy[this.#property] = value } set value(value) { this.#backend.proxy[this.#property] = value }
} }