-
Notifications
You must be signed in to change notification settings - Fork 2
/
EventBus.js
51 lines (46 loc) · 1.08 KB
/
EventBus.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
export default class EventBus {
constructor() {
this.events = {};
//alias
this.addEventListener = this.on.bind(this);
this.removeEventListener = this.off.bind(this);
}
on(eventName, handler) {
if (this.events[eventName]) {
this.events[eventName].push(handler);
} else {
this.events[eventName] = [handler];
}
return this;
}
once(eventName, handler) {
const wrapper = () => {
handler();
this.off(eventName, handler);
};
this.on(eventName, wrapper);
return this;
}
emit(eventName, ...params) {
if (!this.events[eventName]) return;
this.events[eventName].forEach(listener => {
listener(...params);
});
return this;
}
offAllEvents() {
Object.keys(this.events).forEach(eveName => {
this.events[eveName] = [];
})
}
off(eventName, handler) {
if (!eventName) return;
if (!handler) {
this.events[eventName] = [];
} else {
const index = this.events[eventName].indexOf(handler);
this.events[eventName].splice(index, 1);
}
return this;
}
}