JavaScript event trusts and jquery support for event trusts

Source: Internet
Author: User
Tags event listener

In my other article, in the final analysis of the JavaScript event bubbling mechanism, I talked a little bit about the understanding of JavaScript Event Trust from the point of view of bubbling mechanism. Now, let's talk about the event by myself.

What is entrusted?

The so-called entrusted, in the practical sense refers to their own affairs entrusted to others on behalf of the treatment. For example, a entrusted B to do certain things, then, a is entrusted to people, B is entrusted.

The real thing is B, that is entrusted to the person, and the entrusted person A is the corresponding information transmitted to the entrusted person B. The things I should have done were given to B to do. For example, in this example:

So what is event trust in our JavaScript?

Event entrusted

Event entrusted agree that we do not have to add event listeners for certain nodes, but instead add event listeners to a parent node of (those nodes). The event listener parses the bubbling event, finds the matching child node element, and then responds to the corresponding event .

How does the event entrust detail work? Let's start with the simple example below. Let's show you how event trusts work.

Let's look at the following code:

<div id= "Box1" class= "Box1" ><p id= "para1" >paragraph 1</p><p id= "Para2" >paragraph 2</p> <p id= "Para3" >paragraph 3</p><p id= "Para4" >paragraph 4</p><p id= "Para5" >paragraph 5 </p></div>
I now want to pop the "Parax is clicked." Prompt box every time you click the P element under Div1. Our general practice is to add the corresponding event listener to each P element:
<script type= "text/javascript" >window.onload = function () {//Join Event listener document.getElementById ("Para1"). AddEventListener ("click", eventperformed);d Ocument.getelementbyid ("Para2"). AddEventListener ("click", eventperformed);d Ocument.getelementbyid ("Para3"). AddEventListener ("click", eventperformed); document.getElementById ("Para4"). AddEventListener ("click", eventperformed);d Ocument.getelementbyid ("Para5"). AddEventListener ("click", eventperformed);}    The event corresponds to function eventperformed (event) {alert (event.target.id+ "is clicked.");} </script>
Yes, the above code is fully capable of implementing the above functions.

We think about this question, assuming that there are very many P elements under this div1, we cannot always write the shape like document.getElementById ("Parax"). AddEventListener ("click", eventperformed); The code snippet, the words are too mechanical! Other than that. Assumptions in the actual application. It is very possible to dynamically generate P elements with JS under Div1. At this point, we also add the event handler function, like this dynamic join action is very likely to be scattered in the very many corners of our application, so the dynamic addition of processing function will be a very painful thing!


Workaround: Take advantage of the mechanism of event bubbling delivery. The event processing logic that is to be completed for this element is entrusted to the parent class node, and the parent node runs the corresponding event processing logic based on the node information that triggered the event.

<script type= "text/javascript" >window.onload = function () {//Join Event listener document.getElementById ("Box1"). AddEventListener ("click", eventperformed);}    Event counterpart function eventperformed (event) {    if (event.target.nodeName = = ' P ')    {    alert (event.target.id+ "is Clicked. ");}    } </script>
Through the code above. The event handler for the P element can be easily bound, and it is not necessary to bind the handler function manually when adding elements dynamically.

It can be seen that the use of event-entrusted can simplify the processing logic of events, avoid unnecessary event-handling functions, and thus save a certain amount of memory.

However, there are drawbacks to event trusts: Assuming that today's DOM elements are divided into very many layers, the trust of the underlying event may be in the process of bubbling the event. The middle of a node is stopped bubbling, so that the event is not delivered to the upper level, then the trust will fail.


jquery's support for event trusts

The support for event-entrusted in jquery has the following functions:

Of Live () and Die (), delegate (), and Undelegate () are paired, each of which is a binding and reconciliation process.

delegate (SELECTOR,[TYPE],[DATA],FN)

The delegate method of jquery is typically prepared for event-entrusted.

Take a look at the corresponding definition:

Delegate (SELECTOR,[TYPE],[DATA],FN)

selector: selector string for the element that the filter triggers the event.

type: One or more events attached to the element. Multiple event values are separated by a space. Must be a valid event.

Data : Additional data passed to the function

fn: a function that executes when an event occurs

Overview:

The specified element (which belongs to the child element of the selected element) joins one or more event handlers and specifies the function to execute when these events occur.

Event handlers that use the delegate () method apply to current or future elements, such as new elements created by the script.

For example, we use jquery to implement the example above:

<script type= "Text/javascript" >$ (function () {                //Let Box1 handle the click event from child element p to entrust $ ("#box1"). Delegate ("P", "click" , function (event) {alert (Event.target.id + "is clicked.");}) </script>

The code above implements the box1 of the Click event of the child element p. Suppose we dynamically add a child element p to box1 in JS, and the corresponding handler function will also be valid for it.

Undelegate ([SELECTOR,[TYPE],FN])

Accordingly, false assumption cancels the corresponding event entrust, can use the following code:

$ ("#box1"). Undelegate ("P", "click");
the use of delegate is to handle the event entrusted to the child elements of an element, namely, the form: $ ("parentelement"). Delegate ("Siblings", "EventType", function); The parentelement element acts as a trusted person for bubbling event handling.

There is also a second way of jquery: The event handling of the element is entrusted to the DOM root node for processing. The way to do this is live () mode:

Live (type, [data], FN)

Type : Event Types

Data : additional additional data

fn: the corresponding handler function

Descriptive narrative: JQuery appends an event handler to all matching elements, even if the element is added later.

Note: This function is abolished since jQuery1.9 and can only be used in the version number of jQuery1.9.

The above functions are implemented in this way:

<script type= "Text/javascript" >$ (function () {$ ("P"). Live ("Click", Function (event) {alert (event.target.id + "is Clicked. ");}) </script>

Die (Type, [fn])

Note: This function is abolished since jQuery1.9 and can only be used in the version number of jQuery1.9.


Removes all previously used. Live () bound events from the element. (This method is exactly the opposite of live.) ) assuming no parameters. All live events that are bound will be removed.

Corresponds to Live (). Unbind, use the following code:

$ ("P"). Die ();

On event binding, JQuery provides a more general function:

On (EVENTS,[SELECTOR],[DATA],FN)

Number of references:

Events: One or more space-delimited event types and optional namespaces, such as "click" or "Keydown.myplugin".

selector: A selector string is used for the descendant of the selector element of the filter's triggering event. Assume the selected < NULL or omitted. When it reaches the selected element. Events are always triggered.

data: Pass Event.data to the event handler when an event is triggered.

fn: The function that is run when the event is triggered. A false value can also be a shorthand for a function that returns FALSE.

Use the above function instead of the ON function:

<script type= "Text/javascript" >$ (function () {$ ("#box1"). On ("click", "P", function (event) {alert ( Event.target.id + "is clicked.");}) </script>
Off (EVENTS,[SELECTOR],[FN])

Removes an event handler for one or more events on the selection element.

The off () method removes the event handler that is bound with. On ().

Remove the trust from the above on binding:

$ ("#box1"). Off ("click", "P");




On the Internet to see the summary of the event entrusted, feel very good, just translate it posted here.    To share with you, if there are errors or omissions, please point out. Click I to view the original text.

Summarize:

The prerequisite is to have a container that agrees with the generic event handler.


Algorithm:

    1. Bind the event handler to the container,
    2. Get Event.target within the event handler function,
    3. The corresponding treatment according to different event.target

Application Scenarios:

    • The same action needs to be handled by an event handler for the child element;
    • Simplifies the structure between different actions

Strengths:

    • Simplifies the process of initialization. The extra event-handling functions are reduced, thus saving memory.
    • Simplifies the DOM node update. Updates for corresponding events
    • Allows to use innerHTML without additional processing.
Disadvantages:
    • First, require events to bubble in IE. Most events will bubble up. But not all of them.

      For other browsers. The capture phase will also work equally well.

    • Second, in theory the trust will cause the browser to load additional, because in the container of arbitrary local events occur, will execute the event handler function, so in most cases the event handler function is in the empty loop (meaningless action). It's usually not a big deal.







JavaScript event trusts and jquery support for event trusts

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.

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.