Last active
February 11, 2017 10:21
-
-
Save JoshCheek/a287b0f8105871d1f18aa7a5b8fad2ac to your computer and use it in GitHub Desktop.
A JS closure thing
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
const actionsFor = state => { | |
const WITH = attrs => actionsFor(Object.assign({}, state, attrs)) | |
return { | |
ADD_NAME: ({ name }) => WITH({names: [name, ...state.names] }), | |
LOG_STATE: () => console.log(state) || actionsFor(state), | |
} | |
} | |
// dispatcher | |
const buildDispatcher = actions => (action, options={}) => | |
actions = actions[action](options) | |
// user using the dispatcher to update their app state | |
const actions = actionsFor({names: ['kris', 'chris']}) | |
const dispatch = buildDispatcher(actions) | |
dispatch('ADD_NAME', { name: 'erica' }) | |
dispatch('LOG_STATE') | |
dispatch('ADD_NAME', { name: 'eric' }) | |
dispatch('LOG_STATE') | |
// original is not updated, only the dispatcher's are | |
actions.LOG_STATE() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment