-
Notifications
You must be signed in to change notification settings - Fork 0
/
customEventEmitter.js
74 lines (62 loc) · 1.78 KB
/
customEventEmitter.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
/*
Write your own Event Emitter
*/
class MyEventEmitter {
constructor() {
this.events = [];
}
addListener(eventName, fn) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(fn);
return this;
}
on(eventName, fn) {
return this.addListener(eventName, fn);
}
off(eventName, fn) {
return this.removeListener(eventName, fn);
}
removeListener(eventName, fn) {
if (!this.events[eventName]) return this;
const filteredListeners = (listener) => listener !== fn;
this.events[eventName] = this.events[eventName].filter(filteredListeners);
return this;
}
emit(eventName, data) {
if (!this.events[eventName]) {
throw new Error(`Can't emit an event. Event ${eventName} doesn't exists. `)
}
const fireCallbacks = (callback) => {
callback(data);
};
this.events[eventName].forEach(fireCallbacks);
}
once(eventName, fn) {
this.events[eventName] = this.events[eventName] || [];
const onceWrapper = () => {
fn();
this.off(eventName, onceWrapper);
}
this.events[eventName].push(onceWrapper);
return this;
}
eventsCount(eventName) {
let fns = this.events[eventName] || [];
return fns.length;
}
rawListeners(eventName) {
return this.events[eventName];
}
}
// Usage
const myEventEmitter = new MyEventEmitter();
const handleMyEvent = (data) => {
console.log("Was fired: ", data);
};
myEventEmitter.on("testEvent", handleMyEvent);
myEventEmitter.emit("testEvent", "Hi"); // Was fired: trigger
myEventEmitter.emit("testEvent", "trigger"); // Was fired: trigger
myEventEmitter.emit("testEvent", "again");
// myEventEmitter.emit('fakeEvent', {});
myEventEmitter.removeListener("testEvent", handleMyEvent);
myEventEmitter.emit("testEvent", "again");