-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
73 lines (65 loc) · 1.33 KB
/
index.ts
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 { on_destroy } from "../utils"
import type { EventHook } from "../utils"
/**
* Utility for creating event hooks
*
*
* @example
* ```ts
* const { on, off, trigger } = createEventHook<string>()
*
* on((param) => console.log(param))
*
* trigger("xxx") // xxx
*
* off((param) => console.log(param))
*
* trigger("xxx") // nothing
*```
*
* @returns - Event hooks
* - `on` - Add a function to the event hook
* - `off` - Remove a function from the event hook
* - `trigger` - Trigger the event hook
*/
export function createEventHook<T = any>(): EventHook<T> {
const fns: Set<(param: T) => void> = new Set()
/**
* Remove a function from the event hook
*
* @param fn - Function to remove
*/
function off(fn: (param: T) => void) {
fns.delete(fn)
}
/**
* Add a function to the event hook
*
* @param fn - Function to add
*
* @returns - Function to remove the function
*/
function on(fn: (param: T) => void) {
fns.add(fn)
const offFn = () => off(fn)
on_destroy(offFn)
return {
off: offFn,
}
}
/**
* Trigger the event hook
*
* @param param - Parameter to pass to the functions
*
* @returns - Promise that resolves when all functions have resolved
*/
function trigger(param: T) {
return Promise.all(Array.from(fns).map((fn) => fn(param)))
}
return {
on,
off,
trigger,
}
}