What is behind the delegate () and live () methods?

What is behind the delegate() and live() methods in jQuery that enable them to work with current and future elements within the page?

+4
source share
3 answers

jQuerys .live() and .delegate() work on the principle that events can β€œbubble” over the DOM tree. This is a short story, it sounds easy, well, it's really quite easy. The presence of a DOM structure, for example

 <html> <body> <div> <span>Foobar</span> </div> </body> </html> 

If a click on the span occurs, for example, the browser checks to see if there are event handlers attached to this range node. If so, they will be fired. If these event handlers do not stop at what is called event propagation , the event swells. This means that your browser checks to see if the div node parent has any event handlers for the click element attached to it, etc ...

Anytime a .stopPropagation() occurs, the event handler may call a method called .stopPropagation() , which will prevent this event from occurring further.

Now the jQuery .live() method .live() always bind an event handler (for example, 'click') to the <body> element. This means that any click event that occurs somewhere on your page (because all other nodes are children of document.body ) will bubble up to <body> , regardless of whether the nodes already exist when .live() called .live() or added later.

The .delegate() method goes one step further. If you are dealing with a very large and deep DOM structure, it seems expensive in terms of performance (and it really is!), So that every event fills a complete tree. You can specify .delegate() generic parent of the node for newly created nodes. If, for example, we go astray with an unordered list that adds new li nodes, just connect any event handler to this <ul> node. All li nodes are child, so their events are bubbling.

+1
source

The delegate and live events connect to the parent element or the body element, and not to the specific element where it occurs.

When you, for example, click on an element, the event event bubble is called by the bubble for the element's parent and further to the body element, until there is an onclick handler that takes care of this. If you use live to connect a click event, it will wait until the event becomes a bubble until the body element, where it will be checked whether the element in which the event occurred is indicated by the selector you specified.

0
source

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


All Articles