-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounterUsingEventFunctionCreator.js
More file actions
60 lines (53 loc) · 1.88 KB
/
Copy pathCounterUsingEventFunctionCreator.js
File metadata and controls
60 lines (53 loc) · 1.88 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
import React from "react";
import {Button, getRandomNumber} from "../helpers";
import {component, newState, asyncAction, parentAction, composeEvents, memoize, eventPreventDefault} from "omreact";
function eventMatch(reducers) {
const reducer = reducers[this.type];
if (reducer) {
return reducer(...this.args);
} else {
throw new Error("Event type not defined in the update function: " + this.type);
}
}
const event = memoize((type, ...args) => {
return {
type: type,
args: args,
match: eventMatch,
withArgs: (...eventArgs) => ({
type: type,
args: args.concat(eventArgs),
match: eventMatch,
}),
};
});
const init = newState({value: 0});
const update = (_event, state, props) => _event.match({
decrement: () =>
update(event("add", -1), state, props),
add: value =>
newState({value: state.value + value}),
addOnePlusTwo: () =>
composeEvents([event("add", 1), event("add", 2)], update, state, props),
fetchRandom: () =>
asyncAction(getRandomNumber(1, 10).then(event("add").withArgs)),
addValueAndMouseButton: (value, ev) =>
update(event("add", ev.button + value), state, props),
cancelEvent: ev =>
asyncAction(eventPreventDefault(ev)),
notifyParent: () =>
parentAction(props.onFinish, state.value),
});
const render = (state, _props) => (
<div>
<Button $onClick={event("decrement")}>DEC</Button>
<Button $onClick={event("add", +1)}>+1</Button>
<Button $onClick={event("addOnePlusTwo")}>+1+2</Button>
<Button $onClick={event("fetchRandom")}>+ASYNC_RANDOM(1..10)</Button>
<Button $onMouseUp={event("addValueAndMouseButton", +1).withArgs}
$onContextMenu={event("cancelEvent").withArgs}>+BUTTON</Button>
<Button $onClick={event("notifyParent")}>Notify parent</Button>
<div>{state.value}</div>
</div>
);
export default component("CounterUsingEventFunctionCreator", {init, render, update});