Created
October 12, 2017 13:03
-
-
Save JamesTheHacker/5ab43d5946f4163e6784507b5837c46e to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* This class is a high level view of how Redux works under the hood. | |
* This example includes no error handling or immutability and is used | |
* purely as an example to demonstrate how Redux works. | |
*/ | |
class FauxRedux { | |
// Just like Redux we accept a reducer, and some initial state | |
constructor(reducer, initialState = {}) { | |
this.store = [ initialState ]; | |
this.reducer = reducer; | |
this.subscribers = []; | |
} | |
// Dispatch an action | |
dispatch(action) { | |
const newState = this.reducer( | |
this.getState(), | |
action | |
); | |
this.store.push(newState); | |
this.notify(action.type); | |
} | |
// Get the latest state from the store | |
getState() { | |
return this.store[this.store.length - 1]; | |
} | |
// Subscribe to notifications | |
subscribe(callback) { | |
this.subscribers.push(callback); | |
} | |
// Notify all subscribers | |
notify(action) { | |
this.subscribers.map( | |
subscriber => subscriber(action) | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment