Skip to content

Instantly share code, notes, and snippets.

@guangningyu
Last active December 28, 2017 14:22
Show Gist options
  • Save guangningyu/d57c9952988d332b8804c779eeae0c96 to your computer and use it in GitHub Desktop.
Save guangningyu/d57c9952988d332b8804c779eeae0c96 to your computer and use it in GitHub Desktop.
Handmade Redux Demo
<!DOCTYPE html>
<html>
<head>
<title>Handmade Redux Demo</title>
</head>
<body>
<div>
Counter:
<span id="counter"></span>
</div>
<button id="inc">
Increment
</button>
<button id="dec">
Decrement
</button>
<!-- call javascript at the bottom of the page -->
<script src="redux_demo.js"></script>
</body>
</html>
let state = {
counter: 0,
};
const listeners = [];
// create a new state based on the action passed
function reducer(state, action) {
switch (action) {
case 'INC':
return {...state, counter: state.counter + 1};
case 'DEC':
return {...state, counter: state.counter - 1};
default:
return state;
}
}
function dispatch(action) {
const newState = reducer(state, action);
if (newState !== state) {
state = newState;
// notify all the listeners of the change
listeners.forEach(listener => listener());
}
}
function subscribe(callback) {
listeners.push(callback);
}
function updateView() {
document.querySelector('#counter').innerText = state.counter;
}
subscribe(updateView);
document.querySelector('#inc').onclick = () => dispatch('INC');
document.querySelector('#dec').onclick = () => dispatch('DEC');
// update view for the first time
updateView();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment