Jump to content

User:Yuchen sun/sandbox

From Wikipedia, the free encyclopedia

Event delegation

[edit]

Event delegation is a technical jargon in JavaScript when facing web design area. It is introduced by jQuery, which is a lightweight library of JavaScript and can be performed on different browsers and platforms.[1][2] jQuery library enable web developers to manipulate HTML pages, process AJAX(Asynchronous JavaScript and XML), event handling and to implement animation effect in a more convenient way.[2] There are tools to help receive and react to the actions generated by user's interactions with the webpage. All these implementation requires no reloading of the page.[3] Event delegation is one of these techniques introduced by jQuery. Using this feature allows web developer to attach an event of several elements to their parent element in order to simplify this process.[4] This depends on the event bubbling mechanism.

Overview

[edit]

In the scenario of interaction between user and webpage, there are a lot of events triggered on different elements. That means there are corresponding parts of code will listen to these events, respond and run every time a user performs an interactive action on the webpage like click, hover and scroll etc. (for more events, click here).[3] In some cases, albeit these elements on which events are triggered are not identical, they have some common attributes and thus have a same parent element. By using event delegation provided by jQuery library, the developer of the webpage can simply add those event listeners and handlers into a parent element to make all its children available to such events. The reason this works is because of a mechanism called event bubbling.[5] The following section will introduce related concepts on which event delegation is based.

How to use

[edit]

Event bubbling

[edit]

The events we talked about here refers to the DOM events, which enable several programming languages including JavaScript to make use of event listeners and event handlers to respond to certain events.[6] In some cases, however, the web developer may want a single event to occur on multiple elements, that means this event may be listened and handled by event handlers in different level. In other words, if a user clicks on a child element, even the listener and handler in its parent element will also be able to capture it and take corresponding actions, and so does its parent's parent and so on until the root element.[5] This is called event bubbling. For example, a user clicks on a cell in a table, this event will travel up to its parent row, and up to table, then body, and in the last the root element window will also be notified of this event.

Delegation example

[edit]

The event bubbling mechanism makes event delegation possible. If we bind a specific event handler and listener to a high-level element, when the high-level element is notified of this event, this will trigger qualified elements to respond to the event all the way from inner to outer.[6] What's more, even element added in the future is eligible.[4] However, we should be aware that even if we could bind listener and handler to the highest-level parent, that doesn't mean you should do it. To prevent the event from traveling all the way up and costing unnecessary extra time, the designer should use parent which is as close as possible to the element on which the event is triggered.[5] Following example shows how event delegation works.

If there is a parent node of table,which including many children node of td:

<table id="parent">
  <tr>
    <td id="child-1">child-1</td>
    <td id="child-2">child-2</td>
    <td id="child-3">child-3</td>
  </tr>
</table>

When the mouse was moved on the td, we want it to show some relative information on a floating window, or click it to trigger a specific action. What we usually do is to add onMouseOver or onClick for every td:

function addListenersforTd(tdNode){
    tdNode.onClick = function clickHandler(){...};
    tdNode.onMouseOver = function mouseOverHandler(){...}
}

window.onload = function(){
    var tbNode = document.getElementById("parent");
    var tdNodes = tbNode.getElementByTagName("td");
    for(var i=0, l = tdNodes.length; i < l; i++){
        addListeners4Td(tdNodes[i]);
    }   
}

If the td in the table is added or deleted frequently, we have to call the addListenersfortd function every time td is added. It definitely increases the probability of error and complexity, moreover decrease the efficiency of webpage. Event delegation is introduced to simplify this process. Through checking the event object's target, you can judge and gain a reference to the source (e.g. clicked node). Following code will meet expectations.

function getEventTarget(e) {
  e = e || window.event;
  return e.target || e.srcElement;
}

function editCell(e) {
    var target = getEventTarget(e);
    if(target.tagName.toLowerCase() =='li') {
        // DO SOMETHING WHEN CLICKED
    }
}

These code means we add an event click listener to the parent table. When the child is clicked, this event will bubble from the child node to the parent node,event an ancestor node. After parent node catch the event, the target.tagName function will judge whether this node is the node that need to be processed. After the judgement, parent will get the node by the e.target and do something that programmer want to do. These steps are a simple process of event delegation.

Pros and cons

[edit]

Pros

[edit]
  1. Reduce the number of functions which should be managed. Lower the probability of collapse.[5]
  2. Increase the flexibility, we can add or modify elements dynamically without concern about event binding.[3]
  3. Improve the efficiency and boost code reuse.[3]

Cons

[edit]
  1. Not every event can use delegation, e.g. blur, focus, load and unload.[7]

More information

[edit]

DOM events: https://developer.mozilla.org/en-US/docs/Web/Events

jQuery API: http://api.jquery.com/

Books: http://jsbooks.revolunet.com

Blog: https://davidwalsh.name/event-delegate

References

[edit]
  1. ^ "jQuery". Wikipedia, the free encyclopedia. 2016-09-09.
  2. ^ a b jquery.org, jQuery Foundation -. "jQuery". jquery.com. Retrieved 2016-09-11.
  3. ^ a b c d Murphey, Rebecca. jQuery Fundamentals. ISBN 9781446671405.
  4. ^ a b jquery.org, jQuery Foundation -. "Understanding Event Delegation | jQuery Learning Center". learn.jquery.com. Retrieved 2016-09-11.
  5. ^ a b c d jquery.org, jQuery Foundation -. "Introducing Events | jQuery Learning Center". learn.jquery.com. Retrieved 2016-09-11.
  6. ^ a b "DOM events". Wikipedia, the free encyclopedia. 2016-06-09.
  7. ^ Lindley, Code. jQuery Cookbook. pp. 189–190. ISBN 9780596159771.