Skip to content

Instantly share code, notes, and snippets.

@keithamus
Created July 11, 2022 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithamus/dbe643fdbc32319e75abe30602135cf8 to your computer and use it in GitHub Desktop.
Save keithamus/dbe643fdbc32319e75abe30602135cf8 to your computer and use it in GitHub Desktop.
Reducer State management library, similar to Redux, using EventTarget
class Store extends EventTarget {
constructor(reducer, state) {
super()
this.#reducer = reducer
this.#state = state
}
get state() {
return this.#state
}
dispatch(action) {
this.#state = this.#reducer(this.state, action)
this.dispatchEvent(new Event('change'))
}
}
@keithamus
Copy link
Author

To connect a web component to a store with Decorators:

const connect = store => Super => class extends Super {
  #abortController = null
  connectedCallback() {
    this.#abortController?.abort()
    const {signal} = this.#abortController = new AbortController()
    store.addEventListener('change', () => this.handleChange(store.state), { signal })
  }
  disconnectedCallback() {
    this.#abortController?.abort()
  }
}
const store = new Store((state, action) => {
 // Reducer logic...
})

@connect(store)
class MyElement extends HTMLElement {
  handleChange(newState) {
    // Update logic
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment