JavaScript and the DOM use the Event API to let elements inform their ancestors of things that happen. This works well because each element only ever has exactly one parent (up to the document root), so the path an event takes is linear and reasonably short relative to the size of the document.
But there is no analogue mechanism to propagate events downwards through the DOM:
For a simple example, one can imagine a scenario like this:
<product-search>
<search-box></search-box>
<product-card></product-card>
</product-search>
The API of the search-box
element is easy to build with generic DOM APIs: whenever it internally determines that a user's input should start a search, it emits an event of some sort, presumably something like framework:search
.
The product-search
can then simply listen for said event on itself and automatically becomes very resilient to nesting and other weird HTML shenanigans; users can even use different search components if they're feeling extra creative that day.
Once the product-search
component has received the search event, it needs to propagate the state change back down to the product-card
. This is surprisingly difficult to do using a generic mechanism.
The problem here is that a) product-search
might not want to limit itself to only product-card
children but work with any element that conforms to some generic API, b) the element that needs the notification might be deeply nested within the product-search
, and c) the component might have a large number of children, making a shotgun approach risky from a performance perspective.
As far as I am aware, there is no feature in the DOM API that fully addresses this. Am I just making things too complicated here? Is there an easy way around it?
My best idea here is a compromise that achieves a) and b) by using querySelectorAll("*")
and dispatching a non-bubbling event on every child element indiscriminately.
What do y'all think?
One thought I forgot to add is the possibility to shift the responsibility for the communication to the product-card
; it could, when connected, inspect its own context and install an event listener on product-search
. This ends up causing the same problems as before: We might want to use a different wrapper, the search wrapper might be at any point in the ancestor chain and installing event listeners everywhere might degrade perforamance and respond to events the component actually doesn't care about.