-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
68 lines (56 loc) · 1.62 KB
/
index.html
File metadata and controls
68 lines (56 loc) · 1.62 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
<h1 id="title">Hello</h1>
<button id="add">+</button>
<button id="subtract">-</button>
<button id="addTen">+10</button>
<script>
class createStore {
constructor(initialState) {
this.state = initialState
this.fn = null
}
dispatch(action) {
// REDUCER
switch(action.type) {
case 'INCREMENT': {
const oldCounter = this.state.counter
const newState = {...this.state, counter: oldCounter + action.amount}
this.state = newState
break
}
case 'DECREMENT': {
const oldCounter = this.state.counter
const newState = {...this.state, counter: oldCounter - 1}
this.state = newState
break
}
default:
console.log('Unknown action. Not changing state')
}
console.log(`Counter: ${store.state.counter}`)
this.fn()
}
subscribe(fn) {
this.fn = fn
}
getState() {
return this.state
}
}
const store = new createStore({counter: 0})
store.subscribe(() => document.getElementById('title').innerText = `Counter: ${store.getState().counter}`)
function incrementer(amount) {
return {type: 'INCREMENT', amount: amount}
}
function decrementer(amount) {
return {type: 'DECREMENT', amount: amount}
}
document.getElementById('add').addEventListener('click', () => {
store.dispatch(incrementer(1))
})
document.getElementById('subtract').addEventListener('click', () => {
store.dispatch(decrementer(1))
})
document.getElementById('addTen').addEventListener('click', () => {
store.dispatch(incrementer(10))
})
</script>