@@ -3,17 +3,19 @@ function Emitter(object) {
3
3
return mixin ( object ) ;
4
4
}
5
5
6
- this . _callbacks = { } ;
6
+ this . _callbacks = new Map ( ) ;
7
7
}
8
8
9
9
function mixin ( object ) {
10
10
Object . assign ( object , Emitter . prototype ) ;
11
- object . _callbacks = { } ;
11
+ object . _callbacks = new Map ( ) ;
12
12
return object ;
13
13
}
14
14
15
15
Emitter . prototype . on = function ( event , listener ) {
16
- ( this . _callbacks [ '$' + event ] = this . _callbacks [ '$' + event ] ?? [ ] ) . push ( listener ) ;
16
+ const callbacks = this . _callbacks . get ( event ) ?? [ ] ;
17
+ callbacks . push ( listener ) ;
18
+ this . _callbacks . set ( event , callbacks ) ;
17
19
return this ;
18
20
} ;
19
21
@@ -29,20 +31,17 @@ Emitter.prototype.once = function (event, listener) {
29
31
} ;
30
32
31
33
Emitter . prototype . off = function ( event , listener ) {
32
- // No arguments: remove all callbacks
33
34
if ( event === undefined && listener === undefined ) {
34
- this . _callbacks = { } ;
35
+ this . _callbacks . clear ( ) ;
35
36
return this ;
36
37
}
37
38
38
- // Only event specified: remove all listeners for that event
39
39
if ( listener === undefined ) {
40
- delete this . _callbacks [ '$' + event ] ;
40
+ this . _callbacks . delete ( event ) ;
41
41
return this ;
42
42
}
43
43
44
- // Both event and listener specified: remove the specific listener
45
- const callbacks = this . _callbacks [ '$' + event ] ;
44
+ const callbacks = this . _callbacks . get ( event ) ;
46
45
if ( callbacks ) {
47
46
for ( const [ index , callback ] of callbacks . entries ( ) ) {
48
47
if ( callback === listener || callback . fn === listener ) {
@@ -51,20 +50,23 @@ Emitter.prototype.off = function (event, listener) {
51
50
}
52
51
}
53
52
54
- // Clean up if no more listeners remain for the event
55
53
if ( callbacks . length === 0 ) {
56
- delete this . _callbacks [ '$' + event ] ;
54
+ this . _callbacks . delete ( event ) ;
55
+ } else {
56
+ this . _callbacks . set ( event , callbacks ) ;
57
57
}
58
58
}
59
59
60
60
return this ;
61
61
} ;
62
62
63
63
Emitter . prototype . emit = function ( event , ...arguments_ ) {
64
- let callbacks = this . _callbacks [ '$' + event ] ;
64
+ const callbacks = this . _callbacks . get ( event ) ;
65
65
if ( callbacks ) {
66
- callbacks = [ ...callbacks ] ;
67
- for ( const callback of callbacks ) {
66
+ // Create a copy of the callbacks array to avoid issues if it's modified during iteration
67
+ const callbacksCopy = [ ...callbacks ] ;
68
+
69
+ for ( const callback of callbacksCopy ) {
68
70
callback . apply ( this , arguments_ ) ;
69
71
}
70
72
}
@@ -73,7 +75,7 @@ Emitter.prototype.emit = function (event, ...arguments_) {
73
75
} ;
74
76
75
77
Emitter . prototype . listeners = function ( event ) {
76
- return this . _callbacks [ '$' + event ] ?? [ ] ;
78
+ return this . _callbacks . get ( event ) ?? [ ] ;
77
79
} ;
78
80
79
81
Emitter . prototype . hasListeners = function ( event ) {
0 commit comments