Skip to content

Instantly share code, notes, and snippets.

@peponi
Created October 2, 2018 12: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 peponi/b2377eb1be87ef52160ddd6bd9480ba2 to your computer and use it in GitHub Desktop.
Save peponi/b2377eb1be87ef52160ddd6bd9480ba2 to your computer and use it in GitHub Desktop.
simple one level immutable store object
const store = {
storageIndex: undefined,
debug: false,
state: Object.freeze({
}),
setState(keyword, value) {
if (this.debug) console.log(`STATE: ${keyword}:`, value); // eslint-disable-line no-console
const newObject = Object.assign({}, this.state, { [keyword]: value });
this.state = Object.freeze(newObject);
if (this.storageIndex) localStorage.setItem(this.storageIndex, JSON.stringify(newObject));
},
fillState(obj) {
this.state = Object.freeze(Object.assign({}, obj));
if (this.storageIndex) localStorage.setItem(this.storageIndex, JSON.stringify(this.state));
},
load() {
if (this.storageIndex) {
const storedStuff = localStorage.getItem(this.storageIndex);
if (storedStuff && storedStuff.length) {
this.fillState(Object.freeze(JSON.parse(storedStuff)));
}
}
}
};
export default store;
import store from './store'
store.storageIndex = 'family-guy-reverse-puke'
store.debug = true
store.load()
const viewModel = ({store}) => {
store.setState('clicked', 0)
document.addEventListener('click', e => {
store.setState('clicked', store.state.clicked + 1)
})
}
new viewModel({store})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment