DEV Community

𒎏Wii 🏳️‍⚧️
𒎏Wii 🏳️‍⚧️

Posted on

Up and down again: A missing feature in front end event propagation?

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>


Enter fullscreen mode Exit fullscreen mode

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?

Top comments (0)