Created
May 29, 2019 03:36
-
-
Save cereme/c51fd59803aaa79c87454c8663abd1fe to your computer and use it in GitHub Desktop.
My Global state management
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 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; | |
} | |
} | |
} | |
} |
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 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