-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.js
55 lines (47 loc) · 1.45 KB
/
event.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
46
47
48
49
50
51
52
53
54
55
function EventEmitter() {
this.events = {} //存储所有事件的listener
this._maxListeners = 10
}
EventEmitter.prototype.setMaxListeners = function (num) {
this._maxListeners = num
}
EventEmitter.prototype.listeners = function (event) {
return this.events[event]
}
EventEmitter.prototype.on = EventEmitter.prototype.addListener = function (event, listener) {
if (this.events[event]) {
this.events[event].push(listener)
} else {
this.events[event] = []
this.events[event].push(listener)
}
}
EventEmitter.prototype.emit = function (event, ...rest) {
if (this.events[event]) {
if (this.events[event].length >= this._maxListeners) {
console.error('beyond climax')
} else {
this.events[event].forEach(listener => {
listener.apply(this, rest)
})
}
;
}
}
EventEmitter.prototype.once = function (event, listener) {
let wrapper = (...rest) => {
listener.apply(this, rest)
console.assert(this != global, 'this指向错误')
this.removeListener(event, wrapper)
}
this.on(event, wrapper)
}
EventEmitter.prototype.removeListener = function (event, listener) {
if (this.events[event]) {
this.events[event] = this.events[event].filter(value => value != listener)
}
}
EventEmitter.prototype.removeAllListener = function (event) {
delete this.events[event]
}
module.exports = EventEmitter