-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventEmitter.js
42 lines (37 loc) · 1.13 KB
/
EventEmitter.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
/* 实现一个 EventEmitter(观察者模式) 类,拥有 on, off, once 和 emit 方法 */
function EventEmitter() {
this.eventQueue = {};
}
EventEmitter.prototype = {
constructor: EventEmitter,
on: function(type, handler) {
this.eventQueue[type] = this.eventQueue[type] || [];
this.eventQueue[type].push(handler);
return this;
},
off: function(type, handler) {
let handlers = this.eventQueue[type];
for (let i = 0; i < handlers.length; i++) {
if (handler === handlers[i]) {
this.eventQueue[type].splice(i, 1);
}
}
return this;
},
once: function(type, handler) {
const self = this;
const wrapper = function(...args) {
handler && handler.call(null, ...args);
self.off(type, wrapper);
};
this.on(type, wrapper);
return this;
},
emit: function(type, ...args) {
this.eventQueue[type].forEach((handler)=>{
handler(...args)
})
return this;
},
};
export default new EventEmitter();