Skip to content

Instantly share code, notes, and snippets.

@andresilveirah
Last active February 22, 2016 13:22
Show Gist options
  • Save andresilveirah/54dd8ee2a33e31a30276 to your computer and use it in GitHub Desktop.
Save andresilveirah/54dd8ee2a33e31a30276 to your computer and use it in GitHub Desktop.
A (ultra) simple implementation of a Redux app using the ES6 syntax.
// A crude implementation of a Redux store
// It keeps track of the state of the application and calls the listeners
// whenever there's a action dispatch
const createStore = (reducer) => {
let state;
const listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => listeners.push(listener);
// dispatch an empty action in order to start the initial state
dispatch({ });
return { getState, dispatch, subscribe };
};
// the reducer is a pure function which is the responsible for changing
// the state of the application (without mutating the parameters)
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};
const store = createStore(counter);
const render = () => document.body.innerText = store.getState();
store.subscribe(render);
render();
// bind events to dispatch actions
// Left-click to increment the counter
document.addEventListener('click', () => store.dispatch({ type: 'INCREMENT' }) );
// Right-click to decrement the counter
document.addEventListener('contextmenu', (event) => {
event.preventDefault();
store.dispatch({ type: 'DECREMENT' });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment