DOM Event delegation, domdelegation

Source: Internet
Author: User

DOM Event delegation, domdelegation

DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation ).

When an event is triggered on an element, the following occurs:

The event is dispatched to its targetEventTargetAnd any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by followingEventTarget'S parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and includingDocument.

Event bubbling provides the foundation for event delegation in browsers. now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn ). this is event delegation. here's an example of it in practice:

<ul onclick="alert(event.type + '!')">    <li>One</li>    <li>Two</li>    <li>Three</li></ul>

With that example if you were to click on any of the child<li>Nodes, you wocould see an alert"click!", Even though there is no click handler bound to<li>You clicked on. If we boundonclick="..."To each<li>You wocould get the same effect.

So what's the benefit?

Imagine you now have a need to dynamically add new<li>Items to the above list via DOM manipulation:

var newLi = document.createElement('li');newLi.innerHTML = 'Four';myUL.appendChild(newLi);

Without using event delegation you wowould have to "rebind""onclick"Event handler to the new<li>Element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new<li>To the list and you're done.

This is absolutely fantastic for web apps with event handlers bound to specify elements, where new elements are dynamically created and/or removed in the DOM. with event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.

Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down ). it may not make much of a difference to small pages that unload often (I. e. user's navigate to different pages often ). but for long-lived applications it can be significant. there are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (I. e. they leak), and often this leaked memory is tied to an event binding. with event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor ). these types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. ie I'm looking at you ).

Here are some better concrete code examples of event delegation:

  • How JavaScript Event Delegation Works
  • Event Delegation versus Event Handling
  • JQuery. delegate is event delegation + selector specification
  • JQuery. on uses event delegation when passed a selector as the 2nd parameter
  • Event delegation without a JavaScript library
  • Closures vs Event delegation: takes a look at the pros of not converting code to use event delegation
  • Interesting approach PPK uncovered for delegatingfocusAndblurEvents (which do not bubble)

In W3C and DOM operations, windows and events are both objects. Why do we sometimes see that others use javaswevent?

Window. event is a standard writing method. window is a top-level object, and event is an attribute of window, And the type is also an object.
 
What are the specific functions of javascript event objects?

The event object is valid only when an event occurs (for example, when you click the mouse or press the keyboard ).
The event object is used to indicate the event status,
For example
Elements that trigger the event object (event. srcElement ),
Location of the mouse (event. clientX, event. clientY ),
Press the key (event. keyCode) and so on.

The attributes of the event object include:
AltKey, button, Member, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, propertyName, returnValue, screenX, screenY, delimiter, srcElement, srcFilter, toElement, type, x, y (you can view reference books in detail)

How to Use event:

Definition
Var evt = window. event;
FF cannot get the event object through this method, you can pass the value method:
Element. onclick = function (e ){
Var evt = window. event | e;
...
}

Use event to get the coordinates of the mouse when you click
Element. onclick = function (e ){
Var evt = window. event | e;
Var cursorPOS = {
X: evt. clientX,
Y: clientY
}
}

Use the event object to specify a warning box when you press the Enter key.
Element. onkeydown = function (e ){
Var evt = window. event | e;
If (evt. keyCode = 13 ){
Alert ('press Enter! ');
}
}

Use event to get the DOM object clicked by the mouse
Document. onclick = function (e ){
Var evt = window. event | e;
Var _ target = evt. srcElement | evt.tar get;
Alert (_ target. tagName)
}

For more information, see the teaching materials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.