Home >Web Front-end >JS Tutorial >Up and down again: A missing feature in front end event propagation?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-06 16:34:30894browse

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>


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?

The above is the detailed content of Up and down again: A missing feature in front end event propagation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn