Created
April 16, 2018 05:02
-
-
Save jpenney1/62eba800d9b0e5fe3479240486e03ace to your computer and use it in GitHub Desktop.
Vanilla Javascript flux implementation. Easy to understand and copy into your own project, modifying and extending as necessary.
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, initialState) => { | |
const subscribers = []; | |
let currentState = initialState; | |
return { | |
getState: () => currentState, | |
subscribe: fn => { | |
subscribers.push(fn); | |
fn(currentState); | |
}, | |
dispatch: action => { | |
currentState = reducer(currentState, action); | |
subscribers.forEach(fn => fn(currentState)); | |
} | |
}; | |
}; | |
/* | |
* With native functions like Object.assign, references to | |
* other objects are copies as refences. To create clones of the | |
* referenced object's properties and values, we need to | |
* stringify the object, then parse it: | |
*/ | |
const deepCopy = object => JSON.parse(JSON.stringify(object)); | |
const reducer = (state, action) => { | |
let newState = deepCopy(state); | |
if(action.type === 'INCREMENT') { | |
newState.count++; | |
return newState; | |
} else if (action.type === 'DECREMENT') { | |
newState.count--; | |
return newState; | |
} else { | |
return state; | |
} | |
}; | |
let state = { | |
count: 1 | |
}; | |
let store = createStore(reducer, state); | |
let incrementAction = { | |
type: 'INCREMENT' | |
}; | |
let decrementAction = { | |
type: 'DECEREMENT' | |
}; | |
console.log('Initial: ', store.getState()); | |
store.dispatch(incrementAction); | |
console.log('After incn action: ', store.getState()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment