JQ adds event handlers for future elements-event delegates

Source: Internet
Author: User

With the complexity of the DOM structure and the use of dynamic scripting technology such as Ajax, there are more dynamic elements added, directly with the JQ add click event will be found that the newly added elements can not be directly selected, here will need to use the event delegate method, JQ for the event delegate provides live (), The Dalegate () and on () methods.

Event Delegate

We know that when the DOM dispatches events for each element in the page, the corresponding elements typically handle events during the event bubbling phase. In structures like body > div > A, if you click the A element, the click event Bubbles from a to the Div and body (that is, the Document object). Therefore, the Click event that occurs above a, div and body elements can also be handled. 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).

. Live ()

The new Live () method of JQuery 1.3 uses the following:

$ ("#info_table TD"). Live ("Click", Function () {/* * Show more information */});

Here the. Live () method binds the Click event to the $ (document) object, and only needs to bind to $ (document) once, and then be able to handle the subsequent dynamic load of the clicked event of the cell. When any event is received, the $ (document) object checks the event type and the event target, and if it is the click event and the event target is TD, then the handler entrusted to it is executed.

So far, everything seems to be perfect. Unfortunately, that is not the case. Because the. Live () method is not perfect, it has several major drawbacks:

    • The $ () function finds all TD elements in the current page and creates a jquery object, but does not use the TD element collection when confirming the event target. Instead of using a selector expression to compare with event.target or its ancestors, generating this jquery object creates unnecessary overhead;
    • By default the event is bound to the $ (document) element, and if the DOM nesting structure is deep, event bubbling through a large number of ancestor elements can result in performance loss;
    • It can only be placed behind a directly selected element and cannot be used after the DOM traversal method of concatenating, which is $ ("#infotable TD"). Live ... Yes, but $ ("#infotable"). Find ("TD"). Live ... No
    • Collect TD elements and create jquery objects, but the actual operation is a $ (document) object, puzzling.
The way to solve

To avoid generating unnecessary jquery objects, you can use a hack called "Early Delegates", which is called outside the $ (document). Ready () method. Live ():

(function ($) {    $ ("#info_table TD"). Live ("Click", Function () {/* * Show more information */})) (JQuery);

Here, (function ($) {...}) (JQuery) is an "immediate anonymous function"that forms a closure that prevents naming conflicts. Inside the anonymous function, the $ parameter references the jquery object. This anonymous function will not wait until the DOM is ready to execute. Note that when using this hack, the script must be linked and/or executed in the head element of the page. This timing is chosen because the document element is available, and the entire DOM is far from being generated; If you put the script in front of the end body tag, it makes no sense, because the DOM is fully available at that time.

To avoid the performance penalty caused by event bubbling, jquery supports the use of a context parameter when using the. Live () method, starting with 1.4.

$ ("TD", $ ("#info_table") [0]). Live ("Click", Function () {/* * Show more information */});

In this way, the "trustee" is changed from the default $ (document) to $ ("#infotable") [0], saving the bubbling journey. However, the context parameter used in conjunction with. Live () must be a separate DOM element, so the context object is specified here using $ ("#infotable") [0], even if a DOM element is obtained using the array's index operator.

. Delegate ()

As mentioned earlier, in order to break the limits 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:

$ ("#info_table"). Delegate ("TD", "click", Function () {/* * Show more information */});

Using. Delegate () has the following advantages (or solves the following problem with the. Live () method):

    • Directly binds the target element selector ("TD"), the event ("click") and the handler to the "dragged-side" $ ("#info_table"), without additional collection elements, shortened event propagation paths, and explicit semantics;
    • Support is called after the DOM traversal method of concatenating, which is the support for $ ("table"). Find ("#info"). Delegate ..., supports precise control;

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

Tip: When you use event delegation, event delegation is invalidated if you use. Stoppropagation () To prevent event propagation if other event handlers are registered to the target element.

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;

. On ()

According to the release notes for the jquery 1.7 Beta 1, jquery 1.7 will add a new pair of event methods to solve the inconsistency problem caused by the coexistence of. Bind (),. Live (), and. Delegate ():. On () and. Off (), The following is how on () is implemented:

. On (events [, selector] [, data], handler (EventObject))

A simple event binding such as $ (' button '). On (' click ', Function () {}); and bind () no two.
When you need to bind events to more elements, the priority is given to event delegation, which can bring a performance benefit. Like what:

For example, if the Click event is bound to a Document object, the click event of any element on the page bubbles to the Document object for processing.

Notice the Second optional parameter in the description of. On (): selector. For example, add the second parameter, the selector button:

Results:

When the event bubbles to the Document object, the target of the detection event, if matched with the incoming selector (this is the button), triggers the event, otherwise it is not fired.

Note. On () can also receive an object parameter, the property of which is the event type, and the property value is the event handler function. Here is an example of an official document:

Finally, the original Live () method, the handler function is the default binding on the Document object can not be changed, if the DOM nesting structure is very deep, event bubbling through a large number of ancestor elements will lead to a large performance loss. With the. On () method, the event is only bound to the element that matches the selector expression of the $ () function (in my example above, in order to simply bind to document), it is possible to pinpoint part of the page, and the overhead of event bubbling can be reduced. Delegate () and on () are, after all, implemented with on ():

. On () and. Off (): How to Implement
$ (Elems). On (events, selector, data, FN);
$ (elems). Off (events, selector, FN);
If selector is specified, the event is delegated; otherwise, it is a regular binding. The old and new APIs correspond to the following:

JQ adds event handlers for future elements-event delegates

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.