DOM Events and jquery events are non-tangle

Source: Internet
Author: User
Tags event listener

In JavaScript and jquery, there is a way of handling events, and when we write a program to implement certain functions, we find that using native DOM events and events encapsulated in jquery can achieve the same effect, then perhaps we will think that the difference between them is not very large, Even basically there is no difference. This view is wrong, in fact, when the underlying design of the event function, the event attributes that they assign to the element are implemented by different event binding mechanisms.

Let's start with the surface: we all know that jquery is a library of JavaScript, which is based on the native JavaScript design. This means that the events in jquery are written in JavaScript. This is one of the points, and the most important thing is that they bind events differently, and JavaScript and jquery use different event mechanisms. This is the main difference between them, and then we'll talk about it carefully.

(i) JavaScript events

One. DOM events and their transport mechanisms

First of all we want to understand the events of some knowledge, the composition of events, the events are composed of 3 parts, respectively, event source, event, and event processing. Event sources and events are the most divisions requirements, and there are no handlers.

1. Event Source:

Simply put, it is the element of the bound event,

2. Events

There are many events in the event object in JavaScript, such as Onload,onclick,onmouse, but we know there are built-in events in JavaScript and events in the DOM, and they have many of the same events, But DOM objects in the event object are compared with many more keyboard/mouse events, and some private events about IE (ie can only be used).

3. Event handling

When the event is triggered, the code snippet of the JavaScript to be executed to complete a function. You can not add handlers.

(———) "Event bubbling"

In learning C, the bubble sort, "event bubbling" and it is completely different, so-called event bubbling that is, when we trigger an event, the event will be the first level of its ancestors passed to its ancestor, to the superlative, and its order of delivery for different browsers, is also different;

For IE: Trigger event element--ancestor element--body--html--document;

Advanced Browser: Trigger event element--ancestor element--body--document--window;

That is, the event starts from the root node to the target event (called an event capture), then is triggered on the target event (the target phase), and then back to the document root node (event bubbling). Event bubbling is useful in that he can release us from the interception of events, and we can also listen to the ancestor elements of the target event. It is also because of the nature of the event bubbling, which will cause each of our modules to affect each other, so we have to eliminate his influence.

(-----) Event capture phase

Unlike event bubbling, event capture is the first phase of an event, starting with the document root node, and as the DOM tree moves toward the event target, passing through the DOM's nodes to the event target location, the main function of event capture is to establish a path that, during the bubbling phase, goes back to the node along the path.

(----) Target phase

When an event arrives at the target node, the event enters the target stage. The event is triggered on the target node and then propagates up until it returns to the document root node.

Clears the event effect, which can be cleared by the event.stoppropagation () function under the event object, using Event.cancelbubble=true for IE, to clear the effect.

We use this compatibility notation when writing:

  if (event&&event.stoppropagation)    {              event.stoppropagation ();          }   else {                    event.canclebubble=true;                     }

Say a way to clear the event bubbling: Preventdefault (); This function is also the method of the event object, he and stoppropagation () have some difference;

Preventdefult (), he simply prevents the event handler from executing, but does not prevent the bubbling mechanism,

Stoppropagation (), he can stop the bubbling mechanism, the colleague does not affect the event handler.       

Two. Event blocking

It says the two most common ways to block events, 1.preventDefault (); 2.stopPropagation (); Let's talk about their differences.

1, Preventdefault ()

The Preventdefault () function is used to block the default behavior of the browser, so what is the default behavior of the browser? For example, we have a hyperlink link's <a> tag as an example, when we click on the <a> tag, it triggers the browser default Click event, through the bubbling mechanism, passed to the document, and then by the browser parsing the href content, and open the address in the navigation bar.

With the Preventdefault () function, we can block the default behavior of many browsers, such as scrolling the page when tapping the spacebar.

2.stopPropagation ()

Calling Event.stoppropagation () only prevents subsequent callback functions in the propagation chain from being triggered (the bubbling phase is blocked). It does not block the behavior of the event handler function.

Three. Custom events

Browsers are not the only vectors that can trigger DOM events, and we can create custom events and assign them to any node in your document. These custom events have the same behavior as the usual DOM events. This is the most common method of binding events, such as: Li.onclick,div.onmouseover, which are common custom events.

Four. Agent Events

Agent event Monitoring allows you to use an event listener to listen to a large number of DOM node events, in which case it is a more convenient and high-performance event-monitoring method. For example, if you have a list <ul> contains 100 child elements <li>, and they all need to respond similarly to the Click event, then we may need to query these 100 child elements and add event listeners to them separately. In this case, we will generate 100 independent event listeners. If a new element is added, we also need to add the same listener to it. This way not only the cost is relatively large, maintenance is also more troublesome.

Agent event monitoring allows us to handle this situation more simply. Instead of listening to all of the child element's Click events, we listen to their parent element <ul>. This event bubbles up to <ul> when a <li> element is clicked, triggering a callback function. We can determine which <li> was clicked by checking the Event.target property of the event.

Five-event monitoring and removal monitoring mechanism

(-): Event listener

In the past, the browser's event monitoring mechanism is not the same, but with the gradual standardization of the browser, the event monitoring mechanism is relatively unified, but if you want to listen to Internet Explorer, it is best to use some front-end framework, such as jquery, because these front-end framework encapsulates a good compatibility problem.

            Event listener function: element.addeventlistener (< Event-name>,< Span class= "crayon-h" > <callback>< Span class= "Crayon-sy" >, <use-capture>)

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp             parameter:<event-name> is the event we want to listen to, and he can be a standard event for any DOM (Click,mousedown);

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp             parameter:<callback> is a callback function that, when the event is triggered, is passed to the function as an argument to the corresponding event object and data.

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp             parameter:<event-capture> This parameter returns a Boolean value that is used to observe whether the callback function is triggered in the event capture phase,

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp         (ii): Remove event listener

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp                     we use   Element.removeeventlistener () method to remove the event listener;

                     elementremoveeventlistener (< event-name>< Span class= "Crayon-sy" >, <callback>, < use-capture>< Span class= "Crayon-sy")

< Span class= "crayon-v" > < Span class= "Crayon-sy" > & nbsp           but removeelementlistener one thing to note: You have to have a reference to the callback function that is bound. Simply tune < Span class= "crayon-v" > < Span class= "Crayon-sy" >

< Span class= "crayon-v" > < Span class= "Crayon-sy" > < code>      Element.removeeventlistener (' click '); is not able to achieve the desired effect. In other words, when you remove an event listener, you must have a call to the callback function, which means that the anonymous function cannot be used as a callback function.

Finally, let's take a look at the entire process of DOM events from being triggered to the end of a leave:

For events with customizations: Once the event is triggered, through the event listener mechanism, the browser starts the "event capture" phase, reaches the "target stage", and then performs the corresponding function processing, passing the event to the root directory through the "bubbling mechanism".

The default behavior of the browser is performed in the same way as above, except that it is performed by the function of the default bound of the browse, and is not under your control.

(ii) JQuery events

In fact, the event mechanism of jquery is very simple, relative to the DOM's binding system and principle. Because jquery is the encapsulation of some JS code, he solves a lot of problems in the encapsulation process, such as the most difficult compatibility issues, so it is very convenient to use the jquery framework directly.

There are two ways of event binding for jquery: 1. Binding event, 2: Triggering event;

1. Binding Events

In jquery, he provides us with a number of APIs, such as the Click (), which are called binding events, which are very rigid and inflexible in their way of binding.

So in order to bind multiple events, jquery provides a way to bind events on (), which allows us to bind one or more events to an object at the same time. There is also a api,bind ()

It can also bind one or more events, but bind () and on () are different from; on () Bind events only to matching objects, and bind () is the binding event on all matching elements, so the use of On () is recommended;

2. Triggering events

Trigger () triggers a class of events on each matching element, and this function also causes the default behavior of the browser with the same name, so we need to return a value of false in order to not affect the other parts. This event is an indirect binding event, that is, there is no event binding until the trigger is triggered.

Triggerhandler () has the function of trigger (), but he does not trigger the default behavior of the browser;

Supplemental: Event Broker

The API delegates () function provided by JQuery is used to do event proxies. Adds one or more event handlers to the specified element (the child element of the selected element) and specifies the function to run when these events occur.

jquery Event Unbind

Off (): The event used to unbind the on () mode;

Unbind (): The event used to unbind the bind () method;

Undelegates (): Used to de-delegate tasks in delegates () mode.

In general, I understand the incident is so much, which may appear some unclear situation, do a good job is that you can write code to verify the knowledge points, after all, "practice is the test of truth" the only standard, hope to your study of the event to help it!! Wrote for two days, also read a lot of information, but inevitably error, welcome your treatise. Learn together.

DOM Events and jquery events are non-tangle

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.