-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path8-methods.js
102 lines (82 loc) · 1.88 KB
/
8-methods.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
'use strict';
const emitter = () => {
let events = {};
const ee = {
on: (name, f, timeout = 0) => {
const event = events[name] || [];
events[name] = event;
event.push(f);
if (timeout) setTimeout(() => {
ee.remove(name, f);
}, timeout);
},
emit: (name, ...data) => {
const event = events[name];
if (event) event.forEach((f) => f(...data));
},
once: (name, f) => {
const g = (...a) => {
ee.remove(name, g);
f(...a);
};
ee.on(name, g);
},
remove: (name, f) => {
const event = events[name];
if (!event) return;
const i = event.indexOf(f);
if (i !== -1) event.splice(i, 1);
},
clear: (name) => {
if (name) delete events[name];
else events = {};
},
count: (name) => {
const event = events[name];
return event ? event.length : 0;
},
listeners: (name) => {
const event = events[name];
return event ? event.slice() : [];
},
names: () => Object.keys(events)
};
return ee;
};
// Usage
const ee = emitter();
// on and emit
ee.on('e1', (data) => {
console.dir(data);
});
ee.emit('e1', { msg: 'e1 ok' });
// once
ee.once('e2', (data) => {
console.dir(data);
});
ee.emit('e2', { msg: 'e2 ok' });
ee.emit('e2', { msg: 'e2 not ok' });
// remove
const f3 = (data) => {
console.dir(data);
};
ee.on('e3', f3);
ee.remove('e3', f3);
ee.emit('e3', { msg: 'e3 not ok' });
// count
ee.on('e4', () => {});
ee.on('e4', () => {});
console.log('e4 count', ee.count('e4'));
// clear
ee.clear('e4');
ee.emit('e4', { msg: 'e4 not ok' });
ee.emit('e1', { msg: 'e1 ok' });
ee.clear();
ee.emit('e1', { msg: 'e1 not ok' });
// listeners and names
ee.on('e5', () => {});
ee.on('e5', () => {});
ee.on('e6', () => {});
ee.on('e7', () => {});
console.log('listeners', ee.listeners('e5'));
console.log('names', ee.names());