一个精简的事件系统

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
let eventManage = (function() {
let event = {}
// 触发事件
function dispatchEvent(type, infoData) {
if (event.handlers) {
if (Object.prototype.hasOwnProperty.call(event.handlers, type)) {
for (let i = 0; i < event.handlers[type].length; i++) {
event.handlers[type][i](infoData)
}
}
}
}
// 添加监听
function addEventListener(type, callBack) {
if (!event.handlers) {
Object.defineProperty(event, 'handlers', {
value: {},
enumerable: false,
configurable: true,
writable: true
})
}
if (!event.handlers[type]) {
event.handlers[type] = []
}
event.handlers[type].push(callBack)
}
//移除监听
function removeEventListener(type) {
if (event.handlers) {
if (Object.prototype.hasOwnProperty.call(event.handlers, type)) {
event.handlers[type] = []
}
}
}
return {
event,
eventType,
dispatchEvent,
addEventListener,
removeEventListener
}
})()

export { eventManage }