what is behind of delegate() and live() method?
What开发者_JAVA技巧 is behind of delegate()
and live()
methods in jQuery that give them the ability of working for current and future elements within the page?
jQuery Live() Method And Event Bubbling
jQuerys .live()
and .delegate()
method work on the principle that events may "bubble" up the DOM tree. That is the short story, sounds easy, well it indeed is pretty easy. Having a DOM structure like
<html>
<body>
<div>
<span>Foobar</span>
</div>
</body>
</html>
If a click on the span
occurs for instance, you browser checks if there are any event handlers
bound to that span node. If so, they will get fired. If those event handlers don't stop the such called event propagation
, the event is bubbling up. That means your browser will check if the parent div node
has any event handlers for a click
attached to it and so forth...
At anytime while bubbling up, an event handler may call a method called .stopPropagation()
which will prevent this event from further bubbling up.
Now jQuery's .live()
method will bind the event handler (e.g. 'click') always to the <body>
element. This means that any click
event that occurs somewhere on your page (because all other nodes are children from document.body
) will bubble up to the <body>
, regardless if the nodes are already there while calling .live()
or are added later.
The .delegate()
method goes one step further. If you're dealing with a very huge and deep DOM structure, it seems expensive in terms of performance (and it really is!) to let each event bubble up the complete tree. You can tell .delegate()
a common parent node for newly created nodes. If for instance, we are deadling with an unordered list which we append new li
nodes, it is enough to attach any event handler to that <ul>
node. All li
nodes are children, thus their events are bubbling up.
The delegate
and live
events are hooked up on a parent element or the body
element instead of the specific element where it occurs.
When you for example click on an element, the click event bubbles to the parent of the element and further towards the body element until there is an onclick handler that takes care of it. If you use live
to hook up a click event, it will wait until the event has bubbled up to the body element where it will check if the element where the event originated matches the selector that you have specified.
精彩评论