-
Notifications
You must be signed in to change notification settings - Fork 1
/
EventEmitter.js
68 lines (49 loc) · 1.23 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
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
'use strict';
// const events = require('events');
// const emitter = () => {
// const ee = new event.EventEmitter();
// const emit = ee.emit;
// ee.emit = (...args) => {
// if (args[0] !== '*') emit.apply(ee, args);
// args.apply(ee, args);
// };
// return ee;
// };
//prototype
const EventEmitter = function() {
this.events = {};
};
EventEmitter.prototype.on = function(name, fn) {
const event = this.events[name];
if (event) event.push(fn);
else this.events[name] = [fn];
};
EventEmitter.prototype.emit = function(name, ...data) {
const event = this.events[name];
if (event) event.forEach(fn => fn(...data));
};
const ee = new EventEmitter();
ee.on('event1', data => {
console.dir(data);
});
ee.emit('event1', { a: 5 });
//closure
const emitter2 = () => {
const events2 = {};
return {
on: (name, fn) => {
const event2 = events2[name];
if (event2) event2.push(fn);
else events2[name] = [fn];
},
emit: (name, ...data) => {
const event2 = events2[name];
if (event2) event2.forEach(fn => fn(...data));
}
};
};
const ee2 = emitter2();
ee2.on('SuperName', data => {
console.dir(data);
});
ee2.emit('SuperName', 'Chto-to na trnslite!');