Skip to content

Commit

Permalink
fix parsing events
Browse files Browse the repository at this point in the history
  • Loading branch information
treeder committed Oct 20, 2023
1 parent 992fe2d commit 07679fa
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
10 changes: 9 additions & 1 deletion example/counter-component.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import state from '../state.js'

class CounterComponent extends LitElement {
static properties = {
counter: { type: Number }
counter: { type: Number },
counter2: { type: String },
}

constructor() {
super();
this.counter = 0
this.counter2 = ''
}

connectedCallback() {
Expand All @@ -23,18 +25,24 @@ class CounterComponent extends LitElement {
console.log("counter event", e)
this.counter = e.detail.value
})
state.addEventListener('counter2', (e) => {
console.log("counter2 event", e)
this.counter2 = e.detail.value
})
}

render() {
return html`
<div>${this.counter}</div>
<div>${this.counter2}</div>
<md-filled-button @click=${this.increment}>Increment</md-filled-button>
`
}

increment() {
this.counter++
state.set('counter', this.counter)
state.set('counter2', `c:${this.counter}`)
}

}
Expand Down
11 changes: 8 additions & 3 deletions state.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ export class State extends EventTarget { // implements EventTarget (partially an
this.loadState()

window.addEventListener('storage', (e) => {
// console.log("storage event", e)
if (e.key.startsWith(State.statePrefix)) {
console.log("storage event", e)
let key = e.key.substring(State.statePrefix.length)
let value = null
if (e.newValue) {
value = JSON.parse(e.newValue)
}
this.dispatchEvent(new CustomEvent(key, {
detail: {
action: e.newValue ? 'set' : 'delete',
action: value ? 'set' : 'delete',
key: key,
value: e.newValue,
value: value,
},
}))
}
Expand All @@ -44,6 +48,7 @@ export class State extends EventTarget { // implements EventTarget (partially an
// the alternative way using individual keys
for (let key in localStorage) {
let value = localStorage.getItem(key)
value = JSON.parse(value)
this.stateMap.set(key, value)
}
return state
Expand Down

0 comments on commit 07679fa

Please sign in to comment.