Created
June 3, 2016 17:22
-
-
Save ZhihaoLau/8f05969e2e6444891337638da3eefe80 to your computer and use it in GitHub Desktop.
implement createStore from scratch
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 createStore = (reducer) => { | |
// only this place create the one and only state | |
let state | |
let listeners = [] | |
const getState = () => state | |
const dispatch = (action) => { | |
// change state only by dispatching an action | |
state = reducer(state, action) | |
listeners.forEach(listener => listener()) | |
} | |
const subscribe = (listener) => { | |
listeners.push(listener) | |
// a function for unsubscribing | |
return () => { | |
listeners = listeners.filter(l !== listener) | |
} | |
} | |
// initialize state | |
dispatch({}) | |
return { | |
getState, | |
dispatch, | |
subscribe | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
check Dan's tutorial video for more imformation