mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-27 01:43:22 +00:00
Only register event listeners when needed
Otherwise there could be over 200 listeners on a page.
This commit is contained in:
@@ -15,18 +15,14 @@ export default class PopoutController extends Controller {
|
||||
this.buttonTarget.addEventListener("click", this.show.bind(this));
|
||||
this.buttonTarget.addEventListener("keydown", this.applyKeyAction.bind(this));
|
||||
|
||||
// Close when click or tab outside of dialog. Run async (don't block primary event handlers).
|
||||
this.closeIfOutsideBound = this.closeIfOutside.bind(this); // Store reference for removing listeners later.
|
||||
document.addEventListener("click", this.closeIfOutsideBound, { passive: true });
|
||||
document.addEventListener("focusin", this.closeIfOutsideBound, { passive: true });
|
||||
this.closeIfOutsideBound = this.closeIfOutside.bind(this); // Store reference for managing listeners.
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
// Clean up handlers registered outside the controller element.
|
||||
// (jest cleans up document too early)
|
||||
if (document) {
|
||||
document.removeEventListener("click", this.closeIfOutsideBound);
|
||||
document.removeEventListener("focusin", this.closeIfOutsideBound);
|
||||
this.#removeGlobalEventListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +30,9 @@ export default class PopoutController extends Controller {
|
||||
this.dialogTarget.style.display = "block";
|
||||
this.first_input.focus();
|
||||
e.preventDefault();
|
||||
|
||||
// Close when click or tab outside of dialog.
|
||||
this.#addGlobalEventListeners();
|
||||
}
|
||||
|
||||
// Apply an appropriate action, behaving similar to a dropdown
|
||||
@@ -68,6 +67,8 @@ export default class PopoutController extends Controller {
|
||||
this.buttonTarget.classList.toggle("changed", this.#isChanged());
|
||||
|
||||
this.dialogTarget.style.display = "none";
|
||||
|
||||
this.#removeGlobalEventListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,4 +110,15 @@ export default class PopoutController extends Controller {
|
||||
#enabledDisplayElements() {
|
||||
return this.displayElements.filter((element) => !element.disabled);
|
||||
}
|
||||
|
||||
#addGlobalEventListeners() {
|
||||
// Run async (don't block primary event handlers).
|
||||
document.addEventListener("click", this.closeIfOutsideBound, { passive: true });
|
||||
document.addEventListener("focusin", this.closeIfOutsideBound, { passive: true });
|
||||
}
|
||||
|
||||
#removeGlobalEventListeners() {
|
||||
document.removeEventListener("click", this.closeIfOutsideBound);
|
||||
document.removeEventListener("focusin", this.closeIfOutsideBound);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user