Skip to content

Commit

Permalink
implement more optimized EventHandle.off (#7137)
Browse files Browse the repository at this point in the history
  • Loading branch information
Maksims authored Nov 29, 2024
1 parent 7ef3404 commit 54136e5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/core/event-handle.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class EventHandle {

/**
* @type {string}
* @private
* @ignore
*/
name;

Expand Down Expand Up @@ -81,7 +81,7 @@ class EventHandle {
*/
off() {
if (this._removed) return;
this.handler.off(this.name, this.callback, this.scope);
this.handler.offByHandle(this);
}

on(name, callback, scope = this) {
Expand Down
34 changes: 34 additions & 0 deletions src/core/event-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,40 @@ class EventHandler {
return this;
}

/**
* Detach an event handler from an event using EventHandle instance. More optimal remove
* as it does not have to scan callbacks array.
*
* @param {EventHandle} handle - Handle of event.
* @ignore
*/
offByHandle(handle) {
const name = handle.name;
handle.removed = true;

// if we are removing a callback from the list that is executing right now
// ensure we preserve initial list before modifications
if (this._callbackActive.has(name) && this._callbackActive.get(name) === this._callbacks.get(name)) {
this._callbackActive.set(name, this._callbackActive.get(name).slice());
}

const callbacks = this._callbacks.get(name);
if (!callbacks) {
return this;
}

const ind = callbacks.indexOf(handle);
if (ind !== -1) {
callbacks.splice(ind, 1);

if (callbacks.length === 0) {
this._callbacks.delete(name);
}
}

return this;
}

/**
* Fire an event, all additional arguments are passed on to the event listener.
*
Expand Down

0 comments on commit 54136e5

Please sign in to comment.