jquery Source code Analysis (vii)--Events Module event (ii)

Source: Internet
Author: User
Tags event listener

The previous section explores some of the concepts of events and then looks at jquery's event module.

jquery binds events with several api:.bind ()/.live ()/.delegate ()/.on ()/click (),

Regardless of how it is bound, it is still handled by Addeventlistener/attachevent (IE), just like the jquery selector, regardless of how it is matched, and finally using several interfaces provided by the browser.

So now there's a question, why do the events have to differentiate so many different treatment options?

This involves the DOM event-handling model mentioned earlier, capturing and bubbling , the traditional event handling to an element binding a click event, passing in a callback handle processing. Element.addeventlistener (' click ', Dosomething,false), comparing traditional events to the existence of these problems

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

Second: The bound element must exist;

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

Four: The grammar is too complicated

In view of these problems, the introduction of jquery is to use the mechanism of delegation to deal with the idea.

Talk about event delegation to review the event model mentioned in the previous section. The DOM has an event flow feature, which means that when we trigger a node on a page, events are propagated up or down, called event snapping and event bubbling. , the DOM2.0 model divides the event processing process into three stages: Event capture phase, event target stage, and 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 event is forwarded up the DOM tree and once again accesses 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.

In other words, 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), such as. Live ()

There are multiple APIs in jquery to bind events: No matter what method you use (click/bind/delegate), it is 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 use the on method directly to the happy and directly used. The On () method event handler to the element in the currently selected JQuery object.

in jquery 1.11, the. On () method provides all the functions of binding event handling, the effect is self-evident, in addition to the performance differences, through the delegate event can also be very friendly to support dynamic binding, as long as on the delegate image is the original HTML page elements, because it is events are triggered by JavaScript's event bubbling mechanism to monitor , so all the event listeners are effective for all child elements (including the elements generated by JS), and the memory loss can be effectively saved by not having to bind the events to multiple elements.

With so much to say, jquery offers so many ways to bind, specifically what difference do we have to understand:

(1),. Bind () method: Used to attach an event handler directly to an element, the handler is attached to the currently selected element in the JQuery object, so these elements must already exist in the. bind () binding event, and it is clear that the direct call did not take advantage of the delegation mechanism.

(2), Live () method: Attaches the delegate's event handler to the document element of a page, simplifying the use of event handling on dynamically added content on the page. This is similar to the delegate () method, except that all events are delegated to the Document object for processing, increasing the bubbling processing time. This method has now been deprecated and is not recommended for use. Let's use examples to illustrate:

$ (' 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 of the disadvantages of live too many, here will not repeat.

(3), Delegate (): In order to break through the limitations of the single. Bind () method, implement event delegation and introduce the. Live () method. Later, in order to solve the problem of "event propagation chain" too long , the new version also supports specifying the context object for the. Live () method. In order to solve the problem of unnecessary generation of elements, the version simply introduces a new method directly. Delegate ().

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

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

JQuery lookup (' #element '), and bind the alert function to (' #element) as a parameter of the Click event and the CSS selector ' a '.

The principle of event snooping is that whenever an event bubbles to $ (' #element), it checks to see if the event type is the Click event, and whether the target element (Curtarget) of the event matches the CCS selector. Executes the function if all is satisfied. 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, greatly reducing the event propagation process (event bubbling process).

This shows. The delegate () method is a relatively perfect solution. However, in the case of a simple DOM structure, you can also use. Live ().

(4), on method: In fact,. bind (),. Live (),. Delegate () are all implemented by. On (),. Unbind (),. Die (),. Undelegate () The same is done by. Off (), This interface simply provides a way to uniformly bind events


Generally speaking, although the bind/delegate/live three methods can implement the DOM node event binding, but can use. On () to replace the above 3 methods

Speaking so much, the specific use of the process should use that method?

Here's a summary:

1. Bind the same event for many elements in the DOM; 2. Binds an event to an element that does not already exist in the DOM; 3. The cost of using. bind () is very large, and it hooks the same event handler to all matching DOM elements 4. Do not use. Live (), it is no longer recommended, and there are many issues 5. . Delegate () provides a good way to improve efficiency, and we can add an event handling method to dynamically added elements

In practice, the event delegation mechanism (event-based bubbling) still has shortcomings:
1. Not all events can bubble, such as load, change, submit, focus, BLUR2. Increased management complexity 3. It is not good to impersonate a user to trigger event 4. How to make a choice depends on the actual use of the project.

jquery Source code Analysis (vii)--Events Module event (ii)

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.