Examples of common practical applications for bubbles and event captures?

Can someone provide practical, everyday examples of event bubbles and event capturing in jQuery / javascript? I see all the examples demonstrating these concepts, but they always seem like things you never need in a regular web application.

Both descriptions and code snippets are welcome.

+6
source share
2 answers

Practical bubble event?

With or without jQuery (bearing in mind that you can handle bubble events without using a library), there are a number of scenarios in which you want to structure your code to take advantage of the bubbles.

One example: suppose you have a page where elements are created dynamically, but you want to handle a click on these elements. You cannot bind an event handler directly to them before they exist, but to bind individual handlers to them when they are created is a bit of a pain. Instead, attach an event handler to the container object: click events will bubble from individual elements in the container, but you can still indicate which element was clicked - jQuery simplifies this if you use the appropriate .on() or .delegate() syntax (or even .live() if you have a really old version of jQuery) because it sets this to the element with a click.

 <div id="someContainer"></div> $("#someContainer").on("click", ".dynamicElement", function() { // this is the element, do something with it }); 

This suggests that when you click an element with the "dynamicElement" class, which is a child of the "someContainer", the div does something. It will work regardless of whether the "dynamicElement" element existed when the page was loaded, was later added in response to some other user actions or, possibly, loaded using Ajax.

+8
source

I am dynamically adding images to a div, I plan to use event bubbles to capture onload events in the containing div.

+1
source

Source: https://habr.com/ru/post/909881/


All Articles