Created
June 23, 2016 20:34
-
-
Save AphonicChaos/a9379dbbe3a65fbedd262cf917a58739 to your computer and use it in GitHub Desktop.
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>Micro Redux</title> | |
</head> | |
<body> | |
<button onclick="dispatch(DECREMENT)">-</button> | |
<span id="count"></span> | |
<button onclick="dispatch(INCREMENT)">+</button> | |
</body> | |
<script> | |
// actions. You'd define these to signify the various intereactions a user can have with the app | |
var DECREMENT = "DECREMENT"; | |
var INCREMENT = "INCREMENT"; | |
// the initial state of the application | |
var state = 0; | |
// a reducer describes how to interpret an action as a modification of the current state. This is the "callback" | |
// you are usually asked to provide to reduce(), and says quite simply: given the old state and an action, | |
// return a new state". Note that state manipulation here is pure. Instead of updating state in place (state += | |
// 1), you return a new state. | |
function reducer(state, action) { | |
switch (action) { | |
case INCREMENT: | |
return state + 1; | |
case DECREMENT: | |
return state - 1; | |
default: | |
return state; | |
} | |
} | |
// this would be provided by the framework and would give you a way to say that an action has been performed. | |
// in the real redux, there isn't as much mutation, as you would accumulate state and simply display the most | |
// recent, which would allow for time-travel debugging, which makes it super simple to find out when/where your | |
// app is broken. | |
function dispatch(action) { | |
state = reducer(state, action); | |
var count = document.getElementById("count"); | |
count.innerHTML = state; | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment