-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathevent-emitter.js
73 lines (62 loc) · 1.59 KB
/
event-emitter.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
export default class EventEmitter {
constructor() {
this.listeners = {};
}
on = (event, listener) => {
this.bindEvent(event, listener, false);
}
once = (event, listener) => {
this.bindEvent(event, listener, true);
}
emit = (event, ...args) => {
if (!this.hasBind(event)) {
console.warn(`this event: ${event} don't has bind listener.`);
return;
}
const { listeners, isOnce } = this.listeners[event];
listeners.forEach(listener => listener.call(this, ...args));
if (isOnce) {
this.off(event);
}
}
off = (event, listener) => {
if (!this.hasBind(event)) {
console.warn(`this event: ${event} don't exist.`);
return;
}
// remove all listener
if (!listener) {
delete this.listeners[event];
return;
}
// remove specific listener
const listeners = this.listeners[event].listeners;
listeners.forEach(listener => {
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
});
}
hasBind = event => {
return this.listeners[event]
&& this.listeners[event].listeners
&& this.listeners[event].listeners.length;
}
bindEvent = (event, listener, isOnce = false) => {
if (!event || !listener) {
return;
}
this.listeners[event] = this.listeners[event] || {
isOnce: false,
listeners: []
};
this.listeners[event].isOnce = isOnce;
if (isOnce) {
this.listeners[event].listeners = [listener];
}
else {
this.listeners[event].listeners.push(listener);
}
}
}