Re:Introducing command And commandfor In HTML
by irjoe on Friday March 07, 2025 @05:04PM
(#43295267)
Using document.addEventListener means it will work even if the DOM is updated without having to add new event listeners. If I'm not expecting the DOM to change I would be more inclined to do something like:
The React example seems a little odd as well, if the "open" callback actually called "showPopover()" instead of only calling "setIsOpen" then the "useEffect" could be entirely redundant. The resulting code would be a lot clearer imo.
[ Parent
| on HN ]
Re:Introducing command And commandfor In HTML
by lelandfe on Saturday March 08, 2025 @05:02PM
(#43303948)
> it will work even if the DOM is updated without having to add new event listeners
Nailed it.
And the sibling comment got at it but the "magic phrase" to Google for this technique is "event delegation." Two more phrases: delegation relies on "event bubbling," bubbling can be interrupted with "event capturing." (You will rarely want to capture events, it's JS's `!important` equivalent)
One decent overview: https://javascript.info/bubbling-and-capturing