Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Created June 13, 2017 21:09
Show Gist options
  • Save gvergnaud/2d4a45aeab892450a8895814ad4cb2b7 to your computer and use it in GitHub Desktop.
Save gvergnaud/2d4a45aeab892450a8895814ad4cb2b7 to your computer and use it in GitHub Desktop.
const State = state => new Proxy({
state,
listeners: [],
subscribe(listener) {
this.listeners.push(listener)
return () => this.listeners.filter(x => x !== listener)
},
set(stateUpdates) {
this.state = Object.assign({}, this.state, stateUpdates);
this.listeners.forEach(f => {
f()
})
}
}, {
get(obj, k) {
return obj.state[k] !== undefined && !['set', 'subscribe'].includes(k)
? obj.state[k]
: obj[k]
}
})
const initialState = { name: '' }
const state = State(initialState)
const unsubscribe = state.subscribe(() => {
document.body.innerHTML = `<p>Hello ${state.name}</p>`
})
state.set({ name: 'World' })
unsubscribe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment