Affects Version/s: None
Fix Version/s: Master
Component/s: JS APIs and Utilities
Sprint:S04E01 - The Joshua Tree, S04E02 - The Uplift Party Plan, S04E03 - The Queen is Dead, S04E04 - Ten Summoner's Tales
Git Pull Request:
In some cases, it's not posible or desirable to add listeners on every element like in a container with many elements that all share the same action or whose contents might change. A technique that's commonly used in these cases is Event Delegation which unfortunately is not a standard API at the moment.
Event delegation is often used within frameworks like React.js or Metal.js:
However, for most events, React doesn't actually attach them to the DOM nodes on which you declare them. Instead, React attaches one handler per event type directly at the document node. This is called event delegation. In addition to its performance benefits on large application trees, it also makes it easier to add new features like replaying events.
Event delegation is commonly used inside Liferay DXP's codebase through:
- delegate from the metal-dom package
- delegate from AUI
- Intrinsic delegation within React and Metal components
The goal of this story is to provide a custom delegate implementation that can be used throughout DXP as a replacement of the mentioned direct use cases.
- A delegate method is exported from frontend-js-web that allows to pass
- element The DOM element the event should be listened on
- eventName The name of the event to listen to
- selectorOrTarget Either an element or css selector that should match the event for the listener to be triggered.
- callback Function to be called when the event is triggered. It will receive the normalized event object
- defaultListener Optional flag indicating if this is a default listener. That means that it would only be executed after all non default listeners, and only if the event isn't prevented via `preventDefault`.
- Returns something that can be used to remove the listener
- The method is unit tested and documented