-
Notifications
You must be signed in to change notification settings - Fork 8
/
emitter.js
389 lines (306 loc) · 9.57 KB
/
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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
'use strict';
const events = require('events');
class EventEmitter extends events.EventEmitter {
constructor() {
super();
this._resultFilter = this._resultFilter || undefined;
}
get maxListeners() {
return this.getMaxListeners();
}
set maxListeners(n) {
this.setMaxListeners(n);
}
getResultFilter() {
return this.resultFilter;
}
setResultFilter(filter) {
this.resultFilter = filter;
return this;
}
get resultFilter() {
return this._resultFilter === undefined && EventEmitter.defaultResultFilter || this._resultFilter;
}
set resultFilter(filter) {
if (filter !== undefined && filter !== null && typeof filter !== 'function') {
throw new TypeError('Filter must be a function');
}
this._resultFilter = filter;
}
emit(type, ...args) {
// keep a reference to _resultFilter since the filter function
// could theoretically set a new result filter, leading to
// undefined results
const resultFilter = this.getResultFilter();
const events = this._events;
const domain = this._domain;
const errorMonitor = EventEmitter.errorMonitor;
const results = [];
let handlers;
let needDomainExit = false;
let doError = (type === 'error');
//let emitter = this;
let promise = Promise.resolve();
if (events) {
if (doError && (events[errorMonitor] !== undefined)) {
promise = promise.then(() => this.emit(errorMonitor, ...args));
}
doError = (doError && events.error === undefined);
} else if (!doError) {
return promise.then(() => false);
}
if (doError) {
let er;
if (args.length > 0) {
er = args[0];
}
if (!er) {
er = new Error('Uncaught, unspecified "error" event.');
} else if (!(er instanceof Error)) {
// At least give some kind of context to the user
let err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
er = err;
}
// @deprecated
// TODO : remove domains
if (domain) {
er.domainEmitter = this;
er.domain = domain;
er.domainThrown = false;
promise = promise.then(() => domain.emit('error', er));
}
return promise.then(() => { throw er; });
}
handlers = events && events[type];
if (!handlers) {
return promise;
}
if (domain && this !== process) {
domain.enter();
needDomainExit = true;
}
if (typeof handlers === 'function') {
handlers = [handlers];
}
if (handlers.length) {
promise = handlers.reduce((p, handler) => p.then(() => handler(...args)).then(result => results.push(result)), promise);
}
if (needDomainExit) {
promise = promise.then(() => domain.exit(), err => { domain.exit(); throw err; });
}
return promise.then(() => resultFilter ? results.filter(resultFilter) : results);
}
addListener(type, listener) {
return _addListener(this, type, listener, false);
}
prependListener(type, listener) {
return _addListener(this, type, listener, true);
}
once(type, listener) {
if (arguments.length === 1) {
// return a Promise instance when no callback is given
return new Promise(resolve => {
this.once(type, resolve);
});
} else {
if (typeof listener !== 'function') {
throw new TypeError('"listener" argument must be a function');
}
return this.addListener(type, _onceWrap(this, type, listener));
}
}
prependOnceListener(type, listener) {
if (typeof listener !== 'function') {
throw new TypeError('"listener" argument must be a function');
}
return this.prependListener(type, _onceWrap(this, type, listener));
}
removeListener(type, listener) {
let list, events, position;
if (typeof listener !== 'function') {
throw new TypeError('"listener" argument must be a function');
}
events = this._events;
list = events && events[type];
if (!list) {
return Promise.resolve();
}
if (list === listener || (list.listener && list.listener === listener)) {
if (--this._eventsCount === 0) {
this._events = {};
} else {
delete events[type];
if (events.removeListener) {
return this.emit('removeListener', type, listener);
}
}
} else if (typeof list !== 'function') {
position = -1;
for (let i = list.length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0) {
return Promise.resolve();
}
if (list.length === 1) {
list[0] = undefined;
if (this._eventsCount === 1) {
this._events = {};
this._eventsCount = 0;
return Promise.resolve();
} else {
delete events[type];
}
} else {
list.splice(position, 1);
if (list.length === 1) {
events[type] = list[0];
}
}
--this._eventsCount;
if (events.removeListener) {
return this.emit('removeListener', type, listener);
}
}
return Promise.resolve();
}
removeAllListeners(type) {
let listeners, events;
let promise;
events = this._events;
if (!events) {
return Promise.resolve();
}
// not listening for removeListener, no need to emit
if (!events.removeListener) {
if (arguments.length === 0) {
this._eventsCount = 0;
this._events = {};
} else if (events[type]) {
if (this._eventsCount === 1) {
this._eventsCount = 0;
this._events = {};
} else {
this._eventsCount = this._eventsCount - (typeof events[type] === 'function' ? 1 : events[type].length);
delete events[type];
}
}
return Promise.resolve();
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
const keys = Object.keys(events);
for (let i = 0, key; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
promise = promise ? promise.then(this.removeAllListeners(key)) : this.removeAllListeners(key);
}
promise = promise ? promise.then(this.removeAllListeners('removeListener')) : this.removeAllListeners('removeListener');
this._events = {};
this._eventsCount = 0;
return promise || Promise.resolve();
}
listeners = events[type];
if (typeof listeners === 'function') {
promise = this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
for (let i = listeners.length - 1; i >= 0; --i) {
promise = promise ? promise.then(this.removeListener(type, listeners[i])) : this.removeListener(type, listeners[i]);
}
}
return promise || Promise.resolve();
}
}
EventEmitter.EventEmitter = EventEmitter;
Object.defineProperties(EventEmitter, {
defaultMaxListeners: {
get: function getDefaultMaxListeners() {
return events.EventEmitter.defaultMaxListeners;
},
set: function setDefaultMaxListeners(n) {
events.EventEmitter.defaultMaxListeners = n;
}
},
usingDomains: {
get: function getUsingDomains() {
return events.EventEmitter.usingDomains;
},
set: function setUsingDomains(b) {
events.EventEmitter.usingDomains = b;
}
}
});
EventEmitter.defaultResultFilter = undefined;
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype._resultFilter = undefined;
function _addListener(target, type, listener, prepend) {
let m;
let events;
let existing;
let promise;
if (typeof listener !== 'function') {
throw new TypeError('"listener" argument must be a function');
}
events = target._events;
if (!events) {
events = target._events = {};
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener) {
promise = target.emit('newListener', type, listener.listener ? listener.listener : listener);
}
existing = events[type];
}
if (!existing) {
// Optimize the case of one listener. Don\'t need the extra array object.
existing = events[type] = listener;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = prepend ? [listener, existing] : [existing, listener];
} else {
// If we've already got an array, just add it to the array.
if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
}
// Check for listener leak
if (!existing.warned) {
m = target.maxListeners;
if (m && m > 0 && existing.length > m) {
existing.warned = true;
console.error('warning: possible EventEmitter memory ' +
'leak detected. %d %s listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
existing.length, type);
console.trace();
}
}
}
++target._eventsCount;
return promise || Promise.resolve();
}
function _onceWrap(target, type, listener) {
let fired = false;
function g() {
if (!fired) {
const args = arguments;
fired = true;
return target.removeListener(type, g).then(() => listener.apply(target, args));
}
};
g.listener = listener;
return g;
}
module.exports = EventEmitter;