Created
October 2, 2018 12:29
-
-
Save peponi/b2377eb1be87ef52160ddd6bd9480ba2 to your computer and use it in GitHub Desktop.
simple one level immutable store object
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 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; |
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
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