Created
January 14, 2020 15:59
-
-
Save liamnewmarch/a8d7a98051b5da4248c72cac484baa71 to your computer and use it in GitHub Desktop.
Simple event driven store based on Proxy
This file contains 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
/** | |
* Usage example | |
* | |
* ``` | |
* const myStore = new Store({ | |
* count: 1, | |
* }); | |
* | |
* myStore.addEventListener('change', () => { | |
* console.log(store.state.count); | |
* }); | |
* | |
* myStore.state.count++; | |
* ``` | |
*/ | |
class Store extends EventTarget { | |
constructor(state = {}) { | |
super(); | |
this.state = new Proxy(state, { | |
set: (...args) => { | |
try { | |
return Reflect.set(...args); | |
} catch { | |
return false; | |
} finally { | |
this.dispatchEvent(new Event('change')); | |
} | |
}, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment