jquery event bindings and delegate Instances _jquery

Source: Internet
Author: User

This example describes the jquery event bindings and delegates. Share to everyone for your reference. The specific methods are as follows:

The bindings and delegates for jquery events can be implemented in a variety of ways, on (), Bind (), Live (), delegate (), and one ().

Sometimes we might be able to bind an event as follows:

Copy Code code as follows:
$ ("#div1"). Click (function () {
Alert ("Click to trigger");
});

The event bindings above can be implemented in a variety of ways:

1. On ()

Copy Code code as follows:
Countless parameters
$ ("P"). On ("click", Function () {
Alert ($ (this). text ());
});

Have data parameters
function MyHandler (event) {
alert (Event.data.foo);
}
$ ("P"). On ("click", {foo: "Bar"}, MyHandler)

The On () corresponds to OFF (), which removes the event bindings:

Copy Code code as follows:
var foo = function () {
Code to handle some kind of event
};
... now Foo would be called when paragraphs are clicked ...
$ (' body '). On ("click", "P", foo);

... foo would no longer be called.
$ (' body '). Off ("click", "P", foo);

Off (): Removes the binding on ()
One (): Bind only once.

2. Bind ()

Parameters:
(Type,[data],function (EventObject))
Type: A string containing one or more event types that separates multiple events by a space. such as "click" or "Submit", can also be a custom event name.
Data: An extra Datum object passed as a Event.data property value to an event object

fn: The handler function above the event that is bound to each matching element

(Type,[data],false)
Type: A string containing one or more event types that separates multiple events by a space. such as "click" or "Submit", can also be a custom event name.
Data: An extra Datum object passed as a Event.data property value to an event object

False: Setting the third argument to false invalidates the default action.

Bind multiple event types at the same time:

Copy Code code as follows:
$ (' #foo '). Bind (' MouseEnter mouseleave ', function () {
$ (this). Toggleclass (' entered ');
});

Bind multiple event types/handlers at the same time:

Copy Code code as follows:
$ ("button"). Bind ({
Click:function () {$ ("P"). Slidetoggle ();},
Mouseover:function () {$ ("body"). CSS ("Background-color", "Red");
Mouseout:function () {$ ("body"). CSS ("Background-color", "#FFFFFF");
});

You can pass some additional data before the event is processed.

Copy Code code as follows:
function Handler (event) {
alert (Event.data.foo);
}
$ ("P"). Bind ("click", {foo: "Bar"}, Handler)


Cancels the default behavior and prevents the event from bubbling by returning false.

Copy Code code as follows:
$ ("form"). Bind ("Submit", function () {return false;})

Problems with BIND

If there are 10 columns and 500 rows in the table to bind the hit event, then finding and traversing 5,000 of cells can cause the script to perform significantly slower, while saving 5,000 TD elements and corresponding event handlers can also take up a lot of memory (similar to letting everyone stand in front of the door, etc.).

On the basis of the previous example, if we want to implement a simple photo album application, each page displays only 50 photos of thumbnails (50 cells), the user clicks on the "X page" (or "next page") Link can be dynamically loaded from the server to load another 50 photos. In this case, it seems to be acceptable to use the. bind () method to bind 50 cells to an event.

The truth is not. Using the. bind () method will only bind the 50 cells on the first page to the event, which will not have this click event in cells on the dynamically loaded subsequent page. In other words,. bind () can only bind events that already exist when the call is made, and cannot give future additions to the element binding event (similar to the new employee not receiving the Express).

Event delegates can resolve both of these issues. On the code, just replace the. bind () method with the new. Live () Method of jquery 1.3:

Copy Code code as follows:
$ ("#info_table TD"). Live ("Click", Function () {/* Show more info/});

Here the. Live () method binds the Click event to the $ (document) object (but this is not reflected in the code, which is also.) One of the main reasons for the live () method being criticized in detail later, and only need to give $ (document) Bind once (not 50 times, not 5,000 times), and then be able to handle the click events for subsequent dynamically loaded photo cells. When any event is received, the $ (document) object checks the event type and the event target, and executes the handler that is delegated to it if it is the click event and the event target is TD.

Unbind (): Removes bindings from bind.

3. Live ()

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 the TD elements in the current page and creates the jquery object, but does not use this set of TD elements when confirming the event target. Instead, a selector expression is used to compare with event.target or its ancestor elements, so generating this jquery object can cause unnecessary overhead;
By default, events are 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;
Can only be placed after a directly selected element and cannot be used after the consonant dom traversal method, that is $ ("#info_table TD"). Live ... Yes, but $ ("#info_table"). Find ("TD"). Live ... No
It is puzzling to collect TD elements and create jquery objects, but the actual operation is the $ (document) object.
The way to solve it
To avoid generating unnecessary jquery objects, you can use a hack called "early delegation", which is called outside of the $ (document). Ready () method. Live ():

Copy Code code as follows:
(function ($) {
$ ("#info_table TD"). Live ("Click", Function () {/* Show more info/});
}) (JQuery);

Here, (function ($) {...}) (JQuery) is an "Execute anonymous function immediately" 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. The timing is chosen because the document element is available and the entire DOM is far from being generated, and 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 loss of performance caused by event bubbling, jquery supports the use of the. Live () method in conjunction with a context parameter from 1.4:

Copy Code code as follows:
$ ("TD", $ ("#info_table") [0]). Live ("Click", Function () {/* Show more info/});

In this way, the "trustee" becomes $ ("#info_table") from the default of $ (document) [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 with $ ("#info_table") [0], even if a DOM element is obtained using the index operator of the array.

4. Delegate ()

As mentioned earlier, JQuery 1.3 introduces the. Live () method in order to overcome the limitations of the single. bind () method and implement the event delegate. Later, in order to solve the problem of "event propagation chain" too long, jQuery 1.4 also supports specifying a context object for the. Live () method. In order to solve the problem of unnecessary generation of element sets, JQuery 1.4.2 simply introduced a new method. Delegate ().

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

Copy Code code as follows:
$ ("#info_table"). Delegate ("TD", "click", Function () {/* Show more info/});

The use of. Delegate () has the following advantages (or solves the following problems with the. Live () method):
The target element selector ("TD"), Event ("click") and handler are directly bound to the "dragged" $ ("#info_table"), and the element is not collected, the event propagation path is shortened and the semantics is clear;

Called after the DOM traversal method in consonant, which supports $ ("table"). Find ("#info"). Delegate., support precise control;

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

Tip: When you use an event delegate, the event delegate is invalidated if other event handlers registered with the target element use. stoppropagation () to prevent event propagation.

Undelegate (): removing delegate bindings

I hope this article will help you with your jquery programming.

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.