Mini Redux
by Farzad YZ
HTML
<script>
function createStore(reducer) {
let state;
const listeners = [];
return {
getState() {
return state;
},
dispatch(action) {
state = reducer(state, action);
console.log(state);
listeners.forEach(function(listener) {
listener();
});
return action;
},
subscribe(fn) {
listeners.push(fn);
return function() {
listeners.splice(listeners.indexOf(fn), 1);
}
}
}
}
</script>
<button id="btn">increment</button>
<h2 id="result">0</h2>
<script>
// Reducer
function counterReducer(state = 0, action) {
if (action.type === 'INCREMENT') {
return state + 1;
}
return state;
}
// Store
var store = window.createStore(counterReducer);
store.subscribe(function() {
console.log('update')
document.getElementById('result').innerHTML = store.getState();
});
document.getElementById('btn').addEventListener('click', function() {
console.log('click')
store.dispatch({
type: 'INCREMENT'
});
});
</script>