-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
73 lines (64 loc) · 1.53 KB
/
script.js
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
import {
render,
html,
bind,
useReducer,
useDelegation,
} from 'vomjs';
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
const counterRef = useDelegation('click', target => {
const { dataset: { action } } = target;
switch (action) {
case 'incrementIfOdd':
if (state.count & 1) {
dispatch({type: 'increment'});
}
break;
case 'incrementAsync':
setTimeout(() => {
dispatch({type: 'increment'});
}, 1000);
break;
default:
dispatch({type: target.dataset.action});
break;
}
}, [state.count]);
const createButton = (action, text) => html`
<button
data-delegate="${counterRef}"
data-action="${action}"
>
${text}
</button>
`;
return html`
<div data-ref="${counterRef}">
<p>Count: ${state.count}</p>
${createButton('increment', '+')}
${createButton('decrement', '-')}
${createButton('incrementIfOdd', 'increment if odd')}
${createButton('incrementAsync', 'increment if async')}
</div>
`;
}
function App() {
return html`
${bind(Counter)({initialCount: 0})
}`;
}
render(App, document.getElementById('root'));