>
// reducer function - pure function - principle #3 function counter(state, action) { if (typeof state === 'undefined') { return 0 } switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: return state } } // create redux store - single source of truth - principle #1 var store = Redux.createStore(counter)
// get UI element to render var valueEl = document.getElementById('counterValue') function render() { valueEl.innerHTML = store.getState().toString() } // initial rendering (will render 0) render(); // store subscribes to render(), so for every action, it will call this render() store.subscribe(render)
// buttons click event listeners document.getElementById('increment') .addEventListener('click', () => { // emit action - principle #2 store.dispatch({ type: 'INCREMENT' }) }) document.getElementById('decrement') .addEventListener('click', () => { store.dispatch({ type: 'DECREMENT' }) }) document.getElementById('incrementIfOdd') .addEventListener('click', () => { if (store.getState() % 2 !== 0) { store.dispatch({ type: 'INCREMENT' }) } }) const TIMEOUT_PERIOD = 1000; document.getElementById('incrementAsync') .addEventListener('click', () => { setTimeout(function() { store.dispatch({ type: 'INCREMENT' }) }, TIMEOUT_PERIOD) })