Created
April 20, 2017 00:36
-
-
Save borisd/c08eba0f96b88cac9af5e1a9919ae349 to your computer and use it in GitHub Desktop.
Simple Redux Implementation
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 reducer = (state, action) => action.type == 'INC' | |
? Object.assign({}, state, { counter: state.counter + 1 }) | |
: state; | |
const store = createStore(reducer, { counter: 1 }); | |
const unsubscribe = store.subscribe(() => console.log('Counter: ' + store.getState().counter)); | |
store.dispatch({ type: 'INC' }) | |
store.dispatch({ type: 'INC' }) | |
unsubscribe(); | |
store.dispatch({ type: 'INC' }) |
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(reducer, state) { | |
Object.assign(this, { state, reducer, cbs: [] }); | |
} | |
getState() { | |
return this.state | |
} | |
dispatch(action) { | |
this.state = this.reducer(this.state, action); | |
this.cbs.forEach(cb => cb()); | |
} | |
subscribe(cb) { | |
this.cbs.push(cb); | |
return () => { | |
this.cbs = this.cbs.filter(i => i !== cb); | |
} | |
} | |
} | |
const createStore = (reducer, initialState) => new Store(reducer, initialState); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment