When is it useful to capture DOM events?

12

DOM events scroll through the document tree its target, with a capture phase and a bubbling phase. The default behavior when creating a listener with addEventListener is to treat the event in the bubbling phase. When is it useful to handle events in the capture phase?

    
asked by anonymous 15.06.2014 / 06:20

1 answer

7

I believe this is useful for giving parent elements the "final word" about the events that occur in your children. This allows you to decouple a generic, generic functionality that needs to be implemented in a component as a whole, of the specific functionalities of its subcomponents.

A use case would be to enable parent to simultaneously disable all of its descendants except one - for example, in an interactive help, where sub-elements are highlighted and explained one by one, while others remain inactive. This is something that been breaking my head for some time , because before reading your question I only knew the phase of bubbling. And if we only take it into account, we have only two possibilities:

  • Parent controls all of its descendants individually by applying the readonly and / or disabled property to each of them. This creates a complicated dependency, because whenever an element is added or modified, the parent needs to be adapted accordingly. More complex logics - for example where the mentioned attributes are changed programmatically, or have values other than the standard - would have to be taken into account by parent.

  • Each sub-element is aware of the parent and takes its state into account before dealing with each event. At best, you could apply a decorator to each child's event handler to implement parent logic. One would have to be careful not to forget any of them, and yet there would be a bunch of code repeated by all those elements.

That is, without this capture phase implementing the proposed functionality implies a strong coupling between parent and their descendants. And when that parent is "the whole screen," the code can get very complicated. Dealing - and blocking - these events in the capture phase avoids a relationship of unnecessary dependency, allowing to separate the parent logic from the logic of each of its components, making the program much more modular.

    
15.06.2014 / 08:52