Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Created January 14, 2020 15:59
Show Gist options
  • Save liamnewmarch/a8d7a98051b5da4248c72cac484baa71 to your computer and use it in GitHub Desktop.
Save liamnewmarch/a8d7a98051b5da4248c72cac484baa71 to your computer and use it in GitHub Desktop.
Simple event driven store based on Proxy
/**
* 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