Last active
December 28, 2017 14:22
-
-
Save guangningyu/d57c9952988d332b8804c779eeae0c96 to your computer and use it in GitHub Desktop.
Handmade Redux Demo
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
<!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> |
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
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