Skip to content

Commit

Permalink
Use WeakSet for safe check
Browse files Browse the repository at this point in the history
  • Loading branch information
jzendo committed Nov 19, 2023
1 parent 20fc136 commit ac2c64f
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions ev-emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ proto.once = function( eventName, listener ) {
// set onceEvents hash
let onceEvents = this._onceEvents = this._onceEvents || {};
// set onceListeners object
let onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
onceEvents[ eventName ] = onceEvents[ eventName ] || new global.WeakSet();
// set flag
onceListeners[ listener ] = true;
onceEvents[ eventName ].add( listener );

return this;
};
Expand Down Expand Up @@ -74,13 +74,13 @@ proto.emitEvent = function( eventName, args ) {
let onceListeners = this._onceEvents && this._onceEvents[ eventName ];

for ( let listener of listeners ) {
let isOnce = onceListeners && onceListeners[ listener ];
let isOnce = onceListeners && onceListeners.has( listener );
if ( isOnce ) {
// remove listener
// remove before trigger to prevent recursion
this.off( eventName, listener );
// unset once flag
delete onceListeners[ listener ];
delete onceListeners.delete( listener );
}
// trigger listener
listener.apply( this, args );
Expand Down

0 comments on commit ac2c64f

Please sign in to comment.