Created
January 12, 2017 19:13
-
-
Save amogower/4b69fa10c5c7b6b3da8fe89fea52a954 to your computer and use it in GitHub Desktop.
Redux Concepts (thanks @narendrashetty)
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 action = { | |
| type, // specify the action type | |
| data // optional data can be passed | |
| }; | |
| Store.prototype.dispatch = function(action) { | |
| // based on the action type | |
| // generate a new state of the application, | |
| // by passing it to a reducer | |
| const state = this.reducer(action); | |
| this.state = state; | |
| // Brodcast the new state to all subscribers | |
| }); |
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
| Store.prototype.reducer = function(action) { | |
| // create a clone of the state | |
| let state = Object.assign({}, this.state); | |
| switch(action.type) { | |
| case 'INIT': | |
| state.data = action.data; | |
| return state; | |
| default: | |
| return state; | |
| } | |
| }; |
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 INITIAL_STATE = { | |
| isLoaded: false, | |
| data: [] | |
| }; | |
| function Store() { | |
| this.state = INITIAL_STATE; | |
| }; |
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
| // List to hold all the subscribers | |
| let subscribers = []; | |
| // method used to subscribe for a state change | |
| Store.prototype.subscribe = function(callback) { | |
| subscribers.push(callback); | |
| }; | |
| // This method is used to trigger all the subscribers when the state is changed | |
| Store.prototype.triggerSubscribers = function() { | |
| subscribers.forEach((subscriber) => { | |
| subscriber(this.state); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment