-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventEmitter.js
42 lines (38 loc) · 1.12 KB
/
EventEmitter.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
// https://nodejs.org/dist/latest-v16.x/docs/api/events.html#events
class EventEmitterCustom {
constructor(){
this.events = {};
}
/**
* Register event, will be called by emiter
* @param eventName <string> event name
* @param callback <function> callback function
* @param args <function> optional callbacks
* @returns void
*/
on(eventName, callback, ...args){
args.length ? callback = [callback, args] : callback = [callback];
this.events[eventName] = {
eventName,
callback
};
}
/**
* Trigger registered event
* @param eventName <string> event name
* @param callback <function> callback function
* @param args <any> optional arguments
* @returns void
*/
emit(eventName, arg, ...args){
const event = this.events[eventName];
if (event) {
event.callback.forEach(cb => {
cb(arg, args);
});
}
}
}
const node = new EventEmitterCustom()
node.on("nodeEvent", (arg) => console.log(arg))
node.emit("nodeEvent", "it's work!")