-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
50 lines (39 loc) · 1.1 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
function EventBus() {
let all = {};
function on(event, fn) {
(all[event] || (all[event] = [])).push(fn);
return () => {
off(event, fn);
};
}
function off(event, fn) {
if (all[event]) {
all[event].splice(all[event].indexOf(fn) >>> 0, 1);
}
}
function emit(event, data = {}) {
let listeners = all[event] || [];
if (eventBus.log) {
console.groupCollapsed(`%cEventBus %c${event} %c(${listeners.length})`, 'font-weight: normal', 'font-weight: bold', 'font-weight: normal');
console.log('data', data);
console.log('listeners', listeners);
console.groupEnd();
}
(all[event] || []).slice().map((fn) => { fn(data); });
(all['*'] || []).slice().map((fn) => { fn(data, event); });
}
const eventBus = {
on,
off,
emit,
log: false,
};
return eventBus;
};
export { EventBus };
let eventBus = EventBus();
let { on, off, emit } = eventBus;
export { on };
export { off };
export { emit };
export default eventBus;