Remove valueKey from StoredState

This commit is contained in:
Talia 2024-01-17 14:03:35 +01:00
parent 47994975f9
commit c5c4e973a5

View file

@ -221,16 +221,13 @@ class StorageChangeEvent extends Event {
export class StoredState extends State { export class StoredState extends State {
#storage #storage
#valueKey
constructor(init, options={}) { constructor(init, options={}) {
super({}, options) super({}, options)
this.#storage = options.storage ?? localStorage ?? new MapStorage() this.#storage = options.storage ?? localStorage ?? new MapStorage()
this.#valueKey = options.key ?? 'value'
// Initialise storage from defaults // Initialise storage from defaults
for (let [prop, value] of Object.entries(init)) { for (const [prop, value] of Object.entries(init)) {
if (prop === 'value') prop = this.#valueKey
if (this.#storage[prop] === undefined) if (this.#storage[prop] === undefined)
this.set(prop, value) this.set(prop, value)
} }
@ -246,9 +243,7 @@ export class StoredState extends State {
// Listen for changes from other windows // Listen for changes from other windows
const handler = event => { const handler = event => {
if (event.targetState !== this && event.storageArea == this.#storage) { if (event.targetState !== this && event.storageArea == this.#storage) {
let prop = event.key this.emit(event.key, JSON.parse(event.newValue))
if (prop === this.#valueKey) prop = 'value'
this.emit(prop, JSON.parse(event.newValue))
} }
} }
addEventListener("storage", handler) addEventListener("storage", handler)
@ -256,14 +251,12 @@ export class StoredState extends State {
} }
set(prop, value) { set(prop, value) {
if (prop == "value") prop = this.#valueKey
const json = JSON.stringify(value) const json = JSON.stringify(value)
dispatchEvent(new StorageChangeEvent(this.#storage, prop, json, this)) dispatchEvent(new StorageChangeEvent(this.#storage, prop, json, this))
this.#storage[prop] = json this.#storage[prop] = json
} }
get(prop) { get(prop) {
if (prop == "value") prop = this.#valueKey
const value = this.#storage[prop] const value = this.#storage[prop]
return value && JSON.parse(value) return value && JSON.parse(value)
} }