-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
109 lines (97 loc) · 2.92 KB
/
index.html
File metadata and controls
109 lines (97 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<!DOCTYPE html>
<html>
<head>
<title>Simple Redux example</title>
<script src="./SimpleRedux.js"></script>
</head>
<body>
<div>
<p>
Counter: <span id="counterValue">0</span> times; Clicked:
<span id="clickedValue">0</span> times
<button id="increment">+</button>
<button id="decrement">-</button>
<button id="incrementIfOdd">Increment if odd</button>
<button id="incrementAsync">Increment async</button>
</p>
</div>
<script>
// reducers
function counter(state, action) {
if (typeof state === "undefined") {
return 0;
}
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
}
function clickCounter(state, action) {
if (typeof state === "undefined") {
return 0;
}
switch (action.type) {
case "INCREMENT":
case "DECREMENT":
return state + 1;
default:
return state;
}
}
// middlewares
const logger = (store) => (next) => (action) => {
console.group(action.type);
console.info("dispatching", action);
let result = next(action);
console.log("next state", store.getState());
console.groupEnd();
return result;
};
const thunk = (store) => (next) => (action) => {
typeof action === "function"
? action(store.dispatch, store.getState)
: next(action);
};
var store = SimpleRedux.createStore(
SimpleRedux.combineReducers({ counter, clickCounter }),
SimpleRedux.applyMiddleware(thunk, logger)
);
var counterValue = document.getElementById("counterValue");
var clickedValue = document.getElementById("clickedValue");
function render() {
counterValue.innerHTML = store.getState().counter.toString();
clickedValue.innerHTML = store.getState().clickCounter.toString();
}
render();
store.subscribe(render);
document
.getElementById("increment")
.addEventListener("click", function () {
store.dispatch({ type: "INCREMENT" });
});
document
.getElementById("decrement")
.addEventListener("click", function () {
store.dispatch({ type: "DECREMENT" });
});
document
.getElementById("incrementIfOdd")
.addEventListener("click", function () {
if (store.getState().counter % 2 !== 0) {
store.dispatch({ type: "INCREMENT" });
}
});
document
.getElementById("incrementAsync")
.addEventListener("click", function () {
setTimeout(function () {
store.dispatch({ type: "INCREMENT" });
}, 1000);
});
</script>
</body>
</html>