Skip to content

Instantly share code, notes, and snippets.

@zanonnicola
Last active November 2, 2018 09:34
Show Gist options
  • Save zanonnicola/6e73bff49371686999b29f8375ef6669 to your computer and use it in GitHub Desktop.
Save zanonnicola/6e73bff49371686999b29f8375ef6669 to your computer and use it in GitHub Desktop.
Simple ES6 Singleton. This is a simple implementation it doesn't shield you from all the things but good enough in majority of the cases. Simple to reason about as well.
// In your main file
import ModalStore from './store';
console.log(`Test 1: ${ModalStore.getState().date}`); // Test 1: Fri Nov 02 2018 10:12:02 GMT+0100
setTimeout(() => {
console.log(`Test 2: ${ModalStore.getState().date}`); // Test 2: Fri Nov 02 2018 10:12:02 GMT+0100
}, 500);
// As you can see even though date is a mutable field we have the same value for the instance
setTimeout(() => {
ModalStore.setState({date: '2018'});
console.log(`Test 3: ${ModalStore.getState().date}`); // Test 3: 2018
}, 1000);
const modalHOC = store => {
return class Modal {
constructor(config = {}) {
}
myPublicMethod() {
if(store.getState().isOpen) {
// Do your magic
}
}
}
}
export default modalHOC;
class Store {
constructor() {
this.state = {
// Just for testing. You proably want that this to be empty object or having some defaults
date: new Date()
};
}
getState() {
return this.state;
}
setState(newState) {
this.state = {
...this.state,
...newState
};
}
}
const singleton = new Store();
export default singleton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment