-
Notifications
You must be signed in to change notification settings - Fork 3
/
event.ts
95 lines (79 loc) · 2.3 KB
/
event.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import isEmpty from "../Functions/isEmpty";
import isFunc from "../Functions/isFunc";
import gt from "../Functions/gt";
import isLenZero from "../Array/isZeroLen";
import eq from "../Functions/eq";
let maxCache: number = 15;
const events = new Map();
function _isHaveKeyAndValue(key: string, value: () => void): boolean {
return !isEmpty(key) && isFunc(value);
}
function isSomeFunction(args: any[], value): boolean {
return args.some(arg => {
return eq(arg, value)
})
}
function _addEvent(key: string, value: () => void, once: boolean = false) {
if (_isHaveKeyAndValue(key, value)) {
once && isFunc(value) && ((value as any).once = true)
if (events.has(key)) {
const callBacks = events.get(key)
if (!callBacks.includes(value) && !isSomeFunction(callBacks, value)) {
const keyLen = callBacks.length
if (gt(keyLen, maxCache)) {
console.warn('已超出最大缓存量!请注意内存泄露');
return
}
callBacks.push(value);
}
return;
}
events.set(key, [value]);
}
}
function _deleteKey(key: string) {
let values = events.get(key)
if (isLenZero(values)) {
events.delete(key);
}
}
export function on(key: string, value: (rest?: any) => void) {
_addEvent(key, value)
}
export function once(key: string, value: (rest?: any) => void) {
_addEvent(key, value, true)
}
export function trigger(key: string, ...rest: any[]) {
if (isEmpty(key)) return;
const values = events.get(key);
if (isEmpty(values)) return;
for (let i = 0; i < values.length; i++) {
let value = values[i]
isFunc(value) && value(...rest);
//删除原数组元素,会造成原数组索引变化
value.once && values.splice(i, 1) && trigger(key);
_deleteKey(key);
}
}
export function remove(key) {
!isEmpty(key) && events.has(key) && events.delete(key);
}
export function setMaxCache(num: number) {
maxCache = num
}
export function getMaxCache() {
return maxCache;
}
export function watchCache() {
console.info('缓存事件:', events);
return events
}
export default {
on,
once,
trigger,
remove,
setMaxCache,
getMaxCache,
watchCache
}