-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventEmitter.js
More file actions
127 lines (117 loc) · 2.99 KB
/
eventEmitter.js
File metadata and controls
127 lines (117 loc) · 2.99 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
/**
* This file is part of the project licensed under the MIT License.
* Copyright (c) 2026 Serhii Romanenko
* See LICENSE file in the project root for full license information.
*/
'use strict';
export default class EventEmitter {
/**
* Creates an EventEmitter instance
*/
constructor() {
this.events = new Map();
this.wrappers = new Map();
}
/**
* Delete the event by name, or delete all events if no name was provided
* @param {unknown} name - Event Name
*/
clear(name) {
if (name) {
this.events.delete(name);
} else {
this.events.clear();
}
}
/**
* @param {unknown} name - Event Name
* @returns {number} - Returns the number of registered callbacks or 0.
*/
count(name) {
const event = this.events.get(name);
return event ? event.size : 0;
}
/**
* Runs an event
* @param {unknown} name - Event name
* @param {...unknown} args - Event args
*/
emit(name, ...args) {
const event = this.events.get(name);
if (!event) {
return;
}
for (const fn of event.values()) {
fn(...args);
}
}
/**
*
* @param {unknown} name - Event name
* @returns {Set} - Event's callbacks
*/
listeners(name) {
if (
typeof name !== 'string' ||
name === ''
) {
throw Error('Param name is invalid')
}
const event = this.events.get(name);
return new Set(event);
}
/**
* @returns {Array} Events' names
*/
names() {
return [...this.events.keys()];
}
/**
* Subscribe a unique callback to the event.
* @param {unknown} name - Event name
* @param {(...args: unknown[]) => void} fn - Event callback
*/
on(name, fn) {
const event = this.events.get(name);
if (event) {
event.add(fn);
} else {
this.events.set(name, new Set([fn]));
}
}
/**
* The event will be removed after the first execution
* @param {unknown} name - Event name
* @param {(...args: unknown[]) => void} fn - Event callback
*/
once(name, fn) {
const wrapper = (...args) => {
this.remove(name, wrapper);
fn(...args);
};
this.wrappers.set(fn, wrapper);
this.on(name, wrapper);
}
/**
* Removes the callback
* @param {unknown} name - Event name
* @param {(...args: unknown[]) => void} fn - Event callback
*/
remove(name, fn) {
const event = this.events.get(name);
if (!event) {
return;
}
if (event.has(fn)) {
event.delete(fn);
return;
}
const wrapper = this.wrappers.get(fn);
if (wrapper) {
event.delete(wrapper);
if (event.size === 0) {
this.events.delete(name);
}
}
}
}