JQuery 2.0.3 Source Analysis event bindings-bind/live/delegate/on

Source: Internet
Author: User
Tags event listener

Ext.: http://www.cnblogs.com/aaronjs/p/3440647.html?winzoom=1

Event is the heart of the JavaScript app beating, and by using JavaScript, you can listen for specific events and specify that certain events occur to respond to these events

The foundation of the event does not repeat the explanation, originally is the localization source code analysis realizes, therefore needs to have certain foundation to be OK

In order to better understand the internal implementation of the next step, so the first clear understanding of the event interface Division

Online information is everywhere, but as a jquery series of source analysis, I still need to re-summarize

jquery has several API bindings for events http://www.css88.com/jqapi-1.9/

. Bind ()

. Live ()

. Delegate ()

. On ()

Regardless of how it is bound, in the final analysis or with addeventlistener/attachevent processing, as the selector, regardless of how to match the final or so few browser interface processing

So why do events differentiate so many different treatment options?

This involves the DOM event processing model, which is often referred to as capture and bubbling

Traditional event Handling:

Binds a single click event to an element, passing in a callback handle processing

Element.addeventlistener (' click ', Dosomething,false)

This code is normal.

However, if there are several hundred elements on the page that need to be bound (assuming), then you must bind hundreds of times.

So the problem arises:

First: A lot of event binding, performance consumption, but also need to unbind (ie will leak)

Second: The bound element must be present

Third: Post-generation HTML will have no event bindings and need to be re-bound

Four: The grammar is too complicated

............

Is there a way to optimize it? The answer is yes.

Event delegate

The DOM has an event flow feature, which means that when we trigger a node on a page, events are propagated up or down, event snapping and event bubbling.

Take a picture:

The DOM2.0 model divides the event processing process into three stages: first, the event capture phase, the event target phase, and the event bubbling stage.

Event routing can be divided into 3 phases.

(1). During the event capture (capturing) phase, events are forwarded down the DOM tree, each ancestor node of the target node, up to the target node. For example, if a user clicks a hyperlink, the Click event is forwarded from the document node to the HTML element, the BODY element, and the P element that contains the link. During this process, the browser detects the listener for the event's capture event and runs the event listener.

(2) at the target stage, the browser runs the event listener after it finds the event listener that has been assigned to the target event. The target node is the DOM node that triggers the event. For example, if a user clicks on a hyperlink, the link is the target node (the target node is actually a text node within the hyperlink).

(3). During the bubbling (bubbling) phase, the events are forwarded up the DOM tree, once again accessing the ancestor node of the target element to the document node. Each step in the process. The browser detects event listeners that are not capturing event listeners and executes them.

Event delegation can be implemented by using the mechanism of event propagation (this is bubbling).

Specifically, the event delegate is the event object itself that does not handle the event, but instead delegates the processing task to its parent element or ancestor element, or even the root element (document)

Event optimization for jquery

Such a good feature of jquery is of course not spared, so it derives. Bind (),. Live (). On () and. Delegate ()

The event bindings for jquery have several methods that can be called, with the Click event as an example:

    • click Method
    • Bind method
    • Delegate method
    • On method

Here's a clear idea: no matter what you're using (click/bind/delegate), it's ultimately the jquery bottom that calls the on method to complete the final event binding.

So from a certain point of view in addition to the ease of writing and custom selection, it is better to directly use the on method to the happy and direct

So in the new version of the API, this is written:

.on()Method event handler to the element in the currently selected jquery object. In jquery 1.7, the .on() method provides all the functionality for binding event handling

Performance comparison

Let's have a visual test.

Generate 999 DOM nodes without any processing, memory consumption 2.2M

Binds the Click event to each element, increasing to 5.6M

$ ('. UL a '). Click (function (e) {        alert (' click event ');    });

Delegate Event 2.2M

$ ('. UL '). On (' Click ', ' a ', function (e) {        alert (' click event ');    });

The effect is self-evident, in addition to performance differences, through delegated events can also be very friendly to support dynamic binding

As long as on the delegate object is the original element of the HTML page, because the event is triggered by the JavaScript event bubbling mechanism to monitor, so for all child elements (including the later through JS generated elements) all the event monitoring can be effective, And because it is not necessary to bind multiple elements, the memory loss can be saved effectively.

. Bind ()

.bind()method is used to attach an event handler directly to an element.

The handler is attached to the currently selected element in the jquery object, so the .bind() elements must already exist when the event is bound

It's obvious that it's called directly, not using the delegation mechanism.

. Live ()

Attaches an event handler for a delegate to an element of a page document , simplifying the use of event handling on dynamically added content on the page.

For example:

$ (' a '). Live (' click ', function () {alert ("!!!")});

jquery binds the alert function to the $ (document) element and uses ' click ' and ' a ' as arguments.

Whenever an event bubbles onto the document node, it checks to see if the event is a click event, and whether the target element of the event matches the CSS selector of ' a ', and if so, executes the function.

Because a higher version of jquery provides a better approach, there are no .live() drawbacks to methods, so the .live() method is no longer recommended for use

In particular, use .live() the following issues that occur:

  • Before invoking a .live() method, JQuery Gets the element that matches the specified selector, which is time-consuming for large documents.
  • Chained notation is not supported. For example, $("a").find(".offsite, .external").live( ... );  such a notation is illegal and does not work as expected.
  • Since all .live() events are added to the document element, it is possible to pass the longest and slowest path before the event is processed before it can be triggered.
  • On mobile IOS (IPhone, IPad and IPod Touch), for most elements, click events do not bubble to the body of the document and cannot be used with methods if one of the following conditions is not met .live() :
    1. Use native clickable elements, for example, a or button , because these two elements can bubble to document .
    2. The document.body elements inside are used .on() or .delegate() bound, because mobile IOS only bubbles within the body.
    3. You need the click to bubble to the element to apply the CSS style cursor:pointer (or the parent element contains document.documentElement ). However, it is important to note that this disables the copy/paste feature on the element and, when clicked on an element, causes the element to be highlighted.
  • It is inefficient to call in event handling event.stopPropagation() to prevent event processing from being added to the node after the document. Because the event has been propagated to document the top.
  • .live()The interplay of methods with other event methods can be surprising. For example, $(document).unbind("click") all .live() the click events that were added are removed!

. Delegate ()

In order to overcome the limitations of the single. Bind () method, implement event delegation, JQuery 1.3 introduces the. Live () method. Later, to solve the problem of "event propagation chain" too long, jQuery 1.4 also supported specifying the context object for the. Live () method. To solve the problem of generating a set of unnecessary elements, JQuery 1.4.2 simply introduces a new method. Delegate ().

Using the. Delegate (), the preceding example can be written like this:

$ (' #element). Delegate (' A ', ' click ', function () {alert ("!!!")});

jquery scans the document lookup (' #element ') and uses the Click event and the CSS selector ' a ' as a parameter to bind the alert function to (' #element ') and use the Click event and ' a ' This CSS selector binds the alert function to (' #element) as a parameter.

Whenever an event bubbles to $ (' #element), it checks to see if the event is the click event, and whether the target element of the event matches the CCS selector. If the results of both checks are true, it executes the function.

It can be noted that this process is similar to. Live (), but it binds handlers to specific elements rather than to the root of document

So(ina). LIve()= = (′a′). Live () = = (document). Delegate (' A ')?

Visible, the. Delegate () method is a relatively perfect solution. However, in the case of a simple DOM structure, you can also use. Live ().

. On ()

In fact,. bind (),. Live (),. Delegate () are all implemented by. On (),. Unbind (),. Die (),. Undelegate (), and the same is true through. Off ().

Provides a way to unify bound events

Summarize:

You should use. Live () or. Delegate () instead of. Bind () in the following cases:

    • Binds the same event to many elements in the DOM;
    • Binds an event to an element that does not already exist in the DOM;

The cost of using. bind () is very large, and it hooks the same event handler to all matching DOM elements
Do not use. Live (), it is no longer recommended, and there are many problems
. Delegate () provides a good way to improve efficiency, and we can add an event handling method to dynamically added elements
We can use. On () to replace the above 3 methods

The lack of points is also:

    • Not all events can bubble, such as load, change, submit, focus, Blur
    • Increased management complexity.
    • Not good for simulating user-triggered events

How to make a choice depends on the actual use of the project.

JQuery 2.0.3 Source Analysis event bindings-bind/live/delegate/on

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.