Add forward method do state
This returns a thin wrapper State with its value proxied to a given attribute on the backend state.
This commit is contained in:
parent
2a515dc47d
commit
ae334801d4
1 changed files with 30 additions and 0 deletions
30
state.js
30
state.js
|
@ -85,6 +85,10 @@ export class State extends EventTarget {
|
|||
}
|
||||
}
|
||||
|
||||
forward(property="value") {
|
||||
return new ForwardState(this, property)
|
||||
}
|
||||
|
||||
set(prop, value) {
|
||||
this.#target[prop] = value
|
||||
}
|
||||
|
@ -94,6 +98,32 @@ export class State extends EventTarget {
|
|||
}
|
||||
}
|
||||
|
||||
export class ForwardState extends EventTarget {
|
||||
#backend
|
||||
#property
|
||||
|
||||
constructor(backend, property) {
|
||||
super()
|
||||
this.#backend = backend
|
||||
this.#property = property
|
||||
const ref = new WeakRef(this)
|
||||
const abortController = new AbortController()
|
||||
backend.addEventListener("change", event => {
|
||||
const state = ref.deref()
|
||||
if (state) {
|
||||
const relevantChanges = event.changes.filter(([name]) => name === property)
|
||||
if (relevantChanges.length > 0)
|
||||
state.dispatchEvent(new ChangeEvent(relevantChanges))
|
||||
} else {
|
||||
abortController.abort()
|
||||
}
|
||||
}, {signal: abortController.signal})
|
||||
}
|
||||
|
||||
get value() { return this.#backend.proxy[this.#property] }
|
||||
set value(value) { this.#backend.proxy[this.#property] = value }
|
||||
}
|
||||
|
||||
export class StorageChangeEvent extends Event {
|
||||
constructor(storage, key, value, targetState) {
|
||||
super("storagechange")
|
||||
|
|
Loading…
Reference in a new issue