Skip to content

Instantly share code, notes, and snippets.

@cereme
Created May 29, 2019 03:36
Show Gist options
  • Save cereme/c51fd59803aaa79c87454c8663abd1fe to your computer and use it in GitHub Desktop.
Save cereme/c51fd59803aaa79c87454c8663abd1fe to your computer and use it in GitHub Desktop.
My Global state management
class GlobalState{
constructor(){
this.foo = true;
this.observers = [];
}
_mutateFoo(foo){
this.foo = foo;
for(let component of this.observers){
component.setState({foo: this.foo});
}
}
actionFoo(foo){
this._mutateFoo(foo);
}
subscribeState(component){
this.observers.push(component);
component.setState({
foo: this.foo
});
}
unsubscribeState(component){
for(let i in this.observers){
if(this.observers[i] === component){
this.observers.splice(i,1);
break;
}
}
}
}
import global from './global'
class FooScreen extends Component{
constructor(){
this.state = {
foo: false,
};
}
componentDidMount(){
global.subscribeState(this);
}
componentWillUnmount(){
global.unsubscribeState(this);
}
onBar() {
global.actionFoo(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment