forked from jorgebucaran/hyperapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (37 loc) · 1.16 KB
/
index.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
const listeners = {}
const fx = (subscriber) => (action) => [subscriber, action]
const globalListener = (event) => {
for (const [dispatch, actions] of listeners[event.type])
for (const action of actions) dispatch(action, event)
}
const on = (type) =>
fx((dispatch, action) => {
if (!listeners[type]) {
listeners[type] = new Map()
addEventListener(type, globalListener)
}
listeners[type].set(
dispatch,
(listeners[type].get(dispatch) || []).concat(action)
)
return () => {
const actions = listeners[type].get(dispatch).filter((a) => a !== action)
listeners[type].set(dispatch, actions)
if (
actions.length === 0 &&
listeners[type].delete(dispatch) &&
listeners[type].size === 0
) {
delete listeners[type]
removeEventListener(type, globalListener)
}
}
})
export const onMouseMove = on("mousemove")
export const onMouseDown = on("mousedown")
export const onMouseUp = on("mouseup")
export const onKeyDown = on("keydown")
export const onKeyUp = on("keyup")
export const onClick = on("click")
export const onFocus = on("focus")
export const onBlur = on("blur")