-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtasks.txt
More file actions
129 lines (99 loc) · 2.77 KB
/
tasks.txt
File metadata and controls
129 lines (99 loc) · 2.77 KB
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
'use strict';
/*
- on(name, f, timeout = 0)
- удаление событие через remove созданных через once
- distinct() - метод переключает emitter в режим уникальных обработчиков
- names() : array of string - возвращаем все имена
- listeners(name): array of function - возвращает копию массива подписок
- has(name) : boolean - существуют ли обработчики
- has(name, f): boolean - есть ли функция f в массиве обработчиков
- prepend(name, f) - устанавливает обработчик перед всеми остальными
- insert(name, f, g) - устанавливает обработчик f перед g
------------------
- wrapper, EventEmitter, mixin
- wrapper, factory, prototype
- factory, mixin, functor
- prototype, functor, class
- mixin, class, factory
*/
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);
event.splice(i, 1);
},
clear: (name) => {
if (name) events[name] = [];
else events = {};
},
count: (name) => {
const event = events[name];
return event ? event.length : 0;
},
listeners: (name) => {
const event = events[name];
return 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());