Created
June 13, 2017 21:09
-
-
Save gvergnaud/2d4a45aeab892450a8895814ad4cb2b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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