Events in jquery bind bind (), Live (), on (), delegate ()

Source: Internet
Author: User


events in jquery bind bind (), Live (), on (), delegate ()

When we try to bind some events to the DOM element, I believe these 4 methods are most commonly used. And what is the difference between them? What is the most effective way to do it in any situation?

Through the information found

Conclusion: The cost of using. bind () is very high, it hooks up the same event handler to all the matching DOM elements. Live (), it is no longer recommended, and there are many problems. Delegate () provides a good way to improve efficiency, At the same time we can add an event-handling method to the dynamically added element. We can use. On () instead of the 3 methods above, for example:

<ul id= "Members" data-role= "ListView" Data-filter= "true" >
    <!--... more list items ...--> <li
    >
        <a href= "detail.html?id=10" >
            <h3>john resig (author of jquery) </h3>
            <p>< Strong>jquery Core lead</strong></p>
            <p>boston, United states</p>
        </a>
    </li>
    <!--... more list items ...-->
</ul>


Bind ():

. Bind () is the most direct binding method that binds event types and processing functions to DOM element, which is the oldest, and also solves the problem of browser compatibility in event handling. But this method has some performance problems, look at the following code:

/* The. Bind () method attaches the event handler directly to 
   the DOM element in question ("#members li a"). The. Click () method 
   was just a shorthand way to write the. bind () method. */

$ ("#members li a"). Bind ("click", Fu Nction (e) {}); 


The above two lines of code accomplish the same task, which is to add the event handler to all the matching <a> elements. There are some problems with efficiency, on the one hand, we implicitly add click handler to all a tags, the process is expensive, on the other hand, in the execution of the time is also a waste, Because they do the same thing and are executed again and again (for example, we can hook it up to their parent element, and by bubbling we can differentiate each of them and then execute the event handler).

Advantage: This approach provides a convenient and simple binding event to elements on the compatibility solution of event handling between various browsers. Click (),. Hover () ... These very handy event bindings, all of which are a simplified approach to bind, are very good for the element chosen by the ID, not just a quick hook up (because a page has only one ID), and when the event occurs, the handler can be executed immediately (relative to the back of live, Delegate) Implementation method

Disadvantage: It will bind the event to all the selected elements it will not bind to the elements that are dynamically added after it has been executed. You can do bind () when the page loads, so you may have an efficiency problem.

. Live ()

The Live () method uses the concept of an event delegate to handle the binding of events. It is the same as using. bind () to bind events. The live () method binds the corresponding event to the root element of the element you selected, that is, on the document element. So all the events bubbling up can be handled with the same handler. Its processing mechanism is that, once the event bubbles onto the document, jquery will look for selector/event metadata and then decide that handler should be invoked. jquery 1.8.2 's source code:

if (Delegatecount &&! ( Event.button && Event.type = = "click") {for (cur = event.target; cur!= this; cur = cur.parentno de | |
                This) {//Don ' t process clicks (a) on disabled elements (#6911, #8165, #11382, #11764)
                    if (cur.disabled!== true | | | | event.type!== "click") {Selmatch = {};
                    matches = [];
                        for (i = 0; i < Delegatecount i++) {handleobj = handlers[i];

                        sel = Handleobj.selector;
                                if (selmatch[sel] = = undefined) {selmatch[sel] = handleobj.needscontext? JQuery (SEL, this). Index (cur) >= 0:jquery.find (sel, this, nu
                        ll, [cur]). length;
     } if (selmatch[sel)) {Matches.push (handleobj);                   } if (matches.length) {Handlerqueu
                    E.push ({elem:cur, matches:matches}); }
                }
            }
        }


When handler is executing, there will be some delays because of bubbling participation, but the binding is particularly fast.

/* the. Live () method attaches the event handler to the root level 
   document along with the associated selector and Eve NT Information 
   ("#members li a" & "click") * 

/$ ("#members li a"). Live ("Click", Function (e) {});

The advantage of the above code in comparison to. bind () is that we do not need to bind the event on each element, but only once on the document. Although this is not the quickest way, it is indeed the least wasteful.

Advantage: There is only one event binding here, binding to the document instead of binding to all the elements like bind () the dynamically added Elemtns can still trigger those previously bound events, because the actual binding of the event is on the document You can bind the required events before document ready.

Disadvantage: Starting from 1.7 is not recommended, so you have to start phasing it out. Chaining is not supported properly when using event.stoppropagation () is useless because all the selector/event are bound to document, So when we use the Matchselector method to pick that event to be called, it's very slow when the event element is deep in your DOM tree, there's a performance problem.

. Delegate ()

Delegate () is a bit like. Live (), unlike. Live () is that it does not bind all the event to document, but rather where you decide to put it. The same place as the. Live () is the event delegation.

/* the. Delegate () method behaves in a similar fashion to the. Live () method 
   , but instead of attaching of the event Handl Er to the document, you 
   can choose where it is anchored ("#members"). The selector and 
   event information ("Li a" & "click") would be attached to 
   the "#members" element. *

/$ ( "#members"). Delegate ("Li a", "click", Function (e) {});


Pros: You can choose to put this event on that element. Chaining is correctly supported jquery still needs to iterate through all the selector/event data to decide which child element to match, but because you can decide to put it on that root element, So you can effectively reduce the elements you are looking for. Can be used on dynamically added elements

Disadvantage: There is a need to find that event on that element, although much less than the document, but you still have to waste time looking.


. On ()

Actually. bind (),. Live (),. Delegate () is implemented by. On (),. Unbind (),. Die (),. Undelegate (), and the same is done through. Off (), which is the 1.8.2 source code:

Bind:function (types, data, fn) {return
        this.on (types, NULL, data, FN);
    },
    unbind:function (types, fn) {return
        This.off (types, NULL, FN);
    },

    live:function (types, data, fn) {
        jQuery (This.context). On (Ty PES, this.selector, data, FN);
        return this;
    },
    die:function (types, fn) {
        jQuery (this.context). Off (types, This.selector | | "* *", FN);
        return this;
    },

    delegate:function (selector, types, data, fn) {return
        This.on (types, selector, data, FN );
    },
    undelegate:function (selector, types, fn) {
        //(namespace) or (selector, types [, FN])
        re Turn arguments.length = = 1? This.off (Selector, "* *"): This.off (types, selector | | "* *", FN);
    },


Take a look at how we use. On () to overwrite events registered with the previous pass. Bind (),. Live (),. Delegate ():

/* The jquery. bind (),. Live (), and. Delegate () methods are just one line pass throughs to the 
   new jquery 1.8.2. On () Method */

/Bind
$ ("#members li a"). On ("click", Function (e) {}); 
$ ("#members li a"). Bind ("click", Function (e) {}); 

Live
$ (document). On ("click", "#members li a", function (e) {}); 
$ ("#members li a"). Live ("Click", Function (e) {});

Delegate
$ ("#members"). On ("Click", "Li a", function (e) {}); 
$ ("#members"). Delegate ("Li a", "click", Function (e) {});


Advantage: Providing a way to unify the binding event still provides the advantage of the. Delegate (), of course, if you need to, you can also directly use. bind ()

Cons: It may be a bit of a problem for you, because it hides the details of the three methods we introduced earlier.

Reference:

Http://www.cnblogs.com/moonreplace/archive/2012/10/09/2717136.html

https://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/



Related Article

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.

Tags Index: