The principle of JavaScript event delegation and the event delegation in jquery

Source: Internet
Author: User
Tags deprecated

Concept

The event delegate, in layman terms, is to delegate the event of an element to its parent or to a more external element processing.

Event Flow

The event flow describes the order in which events are received from the page.

Event bubbling: Events begin to be received by the most specific element, and then propagate up to less specific nodes (or documents).

Event capture: Events begin to be received by less specific nodes and then propagate down to the most specific node. It is a reverse process of bubbling with events.

DOM2Event flow defined by a level event consists of three phases:

    • Event capture
    • Target Stage
    • Event bubbling
Principle

Event delegation is implemented by the event bubbling mechanism.

Suppose you have a list that requires clicking on a list item to pop up the corresponding field.

<ul id="myLink">  <li id="1">aaa</li>  <li id="2">bbb</li>  <li id="3">ccc</li></ul>

Do not use event delegates

var myLink = document.getElementById(‘myLink‘);var li = myLink.getElementsByTagName(‘li‘);for(var i = 0; i < li.length; i++) {  li[i].onclick = function(e) {    var e = event || window.event;    var target = e.target || e.srcElement;    alert(e.target.id + ‘:‘ + e.target.innerText);    };}

There are problems with this:

    • Bind events to each list item, consuming memory
    • When there are dynamically added elements, you need to re-bind the event to the element

Using event delegates

var myLink = document.getElementById(‘myLink‘);myLink.onclick = function(e) {  var e = event || window.event;  var target = e.target || e.srcElement;  if(e.target.nodeName.toLowerCase() == ‘li‘) {    alert(e.target.id + ‘:‘ + e.target.innerText);  }};

The code above is to delegate the event to the parent of the list item, which is target judged by the nodeName property below.

You can also bind each list item to its corresponding event. Such as:

var myLink = document.getElementById(‘myLink‘);myLink.onclick = function(e) {  var e = event || window.event;  var target = e.target || e.srcElement;  switch(target.id) {    case ‘1‘:      target.style.backgroundColor = ‘red‘;      break;    case ‘2‘:      alert(‘这是第二项‘);      break;    case ‘3‘:      alert(e.target.id + ‘:‘ + e.target.innerText);      break;    default:      alert(‘...‘);  }};

The above code is done by judging the target properties under which id different events are performed.

Benefits of Event Delegation:

    • You only need to delegate events of the same type element to the parent or to the outside of the element, without having to bind events to all elements, reduce memory footprint, and improve performance
    • Dynamically added elements do not need to rebind events

Places to be aware of:

    • The implementation of an event delegate relies on event bubbling, so events that do not support event bubbling are not suitable for event delegates.

Events that are best suited to use event delegation techniques include,,,, click mousedown mouseup keydown , keyup and keypress . Although mouseover and mouseout events also bubble, it is not easy to handle them properly, and it is often necessary to calculate the location of elements. (Because the event is triggered when the mouse moves from one element to its child node, or when the mouse moves out of the element mouseout .) )

    • Not all event bindings are appropriate for the use of event delegates, and improper use may result in an event being bound to an element that does not require a binding event.
Event delegation in jquery

There are several ways to implement event delegation in jquery:

    • On

On (events, [selector], [data], FN)

// 将 li 的事件委托给它的父元素$(‘#myLink‘).on(‘click‘, ‘li‘, function() {    // todo...});
    • Live

The method has been deprecated in the jquery 1.7 version.

    • Delegate

Delegate (selector, [type], [data], FN)

$(‘#myLink‘).delegate(‘li‘, ‘click‘, function() {    // todo...});

The method has been deprecated in the jquery 3.0 version. In on() lieu.

In,,,, and jquery delegate() live() one() bind() so on are ultimately dependent on() methods to achieve. It is therefore possible to use on() alternative methods directly.

Encapsulates an event delegate method

Places to be aware of:

    • Guaranteed compatibility, including: event binding, Element selector Element.matches , event event Object
    • The callback function this points to
    • In the above example, the child element cannot trigger an event when there are child elements under the target element. The solution is to judge the element during the triggering process, and if the currently triggered element is not the target element, proceed to the element's parentNode lookup, otherwise the loop ends.
/** * [delegateevent description] * @param {[Type]} parentselector parent Element * @param {[type]} targetselector target element * @para m {[Type]} Events event * @param {function} fn callback function * @return {[type]} null */FUNCTI On DelegateEvent (Parentselector, Targetselector, events, fn) {//Event binding compatibility handling function addevent (ele, type, Han    DLE) {if (Ele.addeventlistener) {Ele.addeventlistener (type, handle, false);    } else if (ele.attachevent) {ele.attachevent (' on ' + type, handle);    } else {ele[' on ' + type] = handle; }}//If the element is selected by the specified selector string, the Element.matches () method returns true;  Otherwise, false is returned. For browsers that do not support element.matches () or element.matchesselector (), but support the Document.queryselectorall () method, the following alternatives exist if (!     Element.prototype.matches) {Element.prototype.matches = Element.prototype.matchesSelector | |    Element.prototype.mozMatchesSelector | |     Element.prototype.msMatchesSelector | |     Element.prototype.oMatchesSelector | | Element.prototype. webkitmatchesselector | |      function (s) {var matches = (This.document | | this.ownerdocument). Queryselectorall (s), i = matches.length;                  while (---->= 0 && Matches.item (i)!== this) {} return i >-1;    };       }//Event handling Logic addevent (Parentselector, events, function (e) {//compatibility handling var e = e | | window.event; var t = E.target | |            E.srcelement;      Currenttarget = = = Parentselector var currenttarget = e.currenttarget;  Iterates over and determines whether the target element, if not, proceeds to the parentnode of the element while (!t.matches (targetselector)) {//if the target element jumps out of the loop if (t = = =          Currenttarget) {t = null;        Break      } t = T.parentnode;      } if (t) {//To point the this callback function to the target element Fn.call (T, Array.prototype.slice.call (arguments)); }    });}

Invocation Example:

<ul id="myLink">  <li id="1" class="link"><a href="javascript:;"><span>aaa</span></a></li>  <li id="2" class="link"><a href="javascript:;">bbb</a></li>  <li id="3" class="link">ccc</li></ul>
var myLink = document.querySelector(‘#myLink‘);delegateEvent(myLink, ‘li.link‘, ‘click‘, function() {  console.log(this, this.id + ‘:‘ + this.innerText);});

Resources:

1. Advanced Programming of JavaScript (3rd edition)

* 2, Element.matches () API https://developer.mozilla.org/zh-cn/docs/web/api/element/matches*

The principle of JavaScript event delegation and the event delegation in jquery

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.