-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[IMP] components: use a hook to register/clean up event listeners
Currently, we register event listener on `Ref.el` upong mount and unmount steps of the component lifecycle. However, depending on the component structure, the element of the `Ref` could change from a rendering to another*, preventing the proper cleaing of the listener. This commit introduces a new hook to handle such cases more correctly. * an example can be found in component `SelectionInput`. closes #2469 Signed-off-by: Lucas Lefèvre (lul) <lul@odoo.com>
- Loading branch information
Showing
2 changed files
with
31 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { useEffect } from "@odoo/owl"; | ||
import { Ref } from "../../types"; | ||
|
||
/** | ||
* Manages an event listener on a ref. Useful for hooks that want to manage | ||
* event listeners, especially more than one. Prefer using t-on directly in | ||
* components. If your hook only needs a single event listener, consider simply | ||
* returning it from the hook and letting the user attach it with t-on. | ||
* | ||
* Adapted from Odoo Community - See https://github.com/odoo/odoo/blob/saas-16.2/addons/web/static/src/core/utils/hooks.js | ||
*/ | ||
export function useRefListener( | ||
ref: Ref<HTMLElement>, | ||
...listener: Parameters<typeof addEventListener> | ||
) { | ||
useEffect( | ||
(el: HTMLElement | null) => { | ||
el?.addEventListener(...listener); | ||
return () => el?.removeEventListener(...listener); | ||
}, | ||
() => [ref.el] | ||
); | ||
} |