-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·131 lines (116 loc) · 2.51 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* An event utils system written in ES6.
*/
class EventEmitter {
/**
* Creates an instance of EventEmitter.
*/
constructor() {
// Create callback stack
this._events = {};
}
/**
* Add callback to event
*
* @param {string} event
* @param {Function} cb
* @returns {EventEmitter}
*/
on(event, cb) {
// Push callback
(this._events[`$${event}`] = this._events[`$${event}`] || []).push(cb);
return this;
}
/**
* Add callback to event and remove on first call
*
* @param {string} event
* @param {Function} cb
* @returns {EventEmitter}
*/
once(event, cb) {
// Remove listener after callback
let that = this;
function fn() {
that.off(event, fn);
cb.apply(this, arguments);
}
fn.cb = cb;
this.on(event, fn);
return this;
}
/**
* Remove callback from event
*
* @param {string} event
* @param {Function} cb
* @returns {EventEmitter}
*/
off(event, cb) {
// Remove all listeners
if (arguments.length === 0) {
this._events = {};
return this;
}
// Get callbacks of an event
let callbacks = this._events[`$${event}`];
if (!callbacks) {
return this;
}
// Remove all callbacks of a specific event
if (arguments.length === 1) {
delete this._events[`$${event}`];
return this;
}
// Remove specific callback of a specific event
var callback;
for (let i = 0; i < callbacks.length; i++) {
callback = callbacks[i];
if (callback === cb || callback.cb === cb) {
callbacks.splice(i, 1);
break;
}
}
return this;
}
/**
* Emit an event with arguments
*
* @param {string} event
* @param {...args} cbs
* @returns {EventEmitter}
*/
emit(event, ...args) {
// Get callbacks of an event
let callbacks;
if (!(callbacks = this._events[`$${event}`])) {
return this;
}
// Quick clone
callbacks = callbacks.slice(0);
// Invoke all callbacks attached to an event
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](...args);
}
return this;
}
/**
* Return all callbacks attached to an event
*
* @param {string} event
* @returns {Function[]}
*/
listeners(event) {
return this._events[`$${event}`] || [];
}
/**
* Return a boolean if the event has listeners
*
* @param {string} event
* @returns {boolean}
*/
hasListeners(event) {
return !!this.listeners(event).length;
}
}
export default EventEmitter;