Last active
June 8, 2017 05:19
-
-
Save TapaniAla/fa16304c8b2a6ec92bf1c812cbfeb6d7 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/cequnu
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 counter = (state = 0, action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1; | |
case 'DECREMENT': | |
return state - 1; | |
default: | |
return state; | |
} | |
} | |
const createStore = (reducer) => { | |
let state; | |
let listeners = []; | |
const getState = () => state; | |
const dispatch = (action) => { | |
state = reducer(state, action); | |
listeners.forEach(listener => listener()); | |
}; | |
const subscribe = (listener) => { | |
listeners.push(listener); | |
return() => { | |
listeners = listeners.filter(l => l !== listener); | |
} | |
}; | |
// to get reducer to return initial value | |
dispatch({}); | |
return { getState, dispatch, subscribe}; | |
} | |
const store = createStore(counter); | |
const render = () => { | |
document.body.innerText = store.getState(); | |
} | |
// Needed to show initial state 0 | |
store.subscribe(render); | |
// Needed to show initial state 0 | |
render(); | |
document.addEventListener('click', () => { | |
store.dispatch({type:'INCREMENT'}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment