Skip to content

Instantly share code, notes, and snippets.

@jpenney1
Created April 16, 2018 05:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpenney1/62eba800d9b0e5fe3479240486e03ace to your computer and use it in GitHub Desktop.
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.
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