Last active
November 2, 2018 09:34
-
-
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.
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
// 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); |
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 modalHOC = store => { | |
return class Modal { | |
constructor(config = {}) { | |
} | |
myPublicMethod() { | |
if(store.getState().isOpen) { | |
// Do your magic | |
} | |
} | |
} | |
} | |
export default modalHOC; |
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
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