Events in JavaScript

Source: Internet
Author: User

The recent period of time is learning javascript, too much knowledge, need to carry out the actual use and summary, the National Day holiday just have time, wrote the following on the JavaScript summary, may be the understanding of the event is not perfect, I hope readers a lot of guidance, shoot bricks, I would be grateful. All right, just title it.

stream of events in JavaScript

The DOM2 level event specifies that the event flow is divided into 3 phases:

First stage: the event capture phase, first by the document root node window->document->html->body ... Captures an event object from an Outward-bound object to an event Trigger.

The second stage: the target stage, reaching the target event position, triggering the event;

Phase Three: Event bubbling, then bubbling from the target event location toward the Document's root node Direction.

The sequence of event capture and event bubbling is shown in steps (1), (2), (3).

Here's an easy way to do the above capture and bubbling experiment:

The environment is a common Chrome browser with the following code:

1<! DOCTYPE html>234<title>Event</title>56<body>7<div id= "btn-big-test" >Div18<br/>9<br/>Ten<div id= "btn-big-test2" >div2</div> one</div> a</body> -<script type= "text/javascript" > - varel = document.getElementById (' btn-big-test '); the varEl2 = document.getElementById (' btn-big-test2 ')); -El.addeventlistener (' Click ',function(event) { -Console.log ("bubbling 1>>" + date.parse (NewDate ())); -},false); +  -El.addeventlistener (' Click ',function() { +Console.log ("capture 1>>" + date.parse (NewDate ())); a},true); atEl2.addeventlistener (' Click ',function() { -Console.log ("bubbling 2>>" + date.parse (NewDate ())); -},false); -  -El2.addeventlistener (' Click ',function() { -Console.log ("capture 2>>" + date.parse (NewDate ())); in},true);
View Code

The results of the operation are as Follows:

It seems the result is not what we thought it would be. perform the capture before bubbling, then the question comes, what is the Problem. Think about the following two registration events to change the Order:

1 function () {2     console.log ("capture 2>>" + date.parse (new  Date ())); 3 true ); 4 5 function () {6     console.log ("bubbling 2>>" + date.parse (new  Date ())); 7 false);
View Code

The results of the operation are as Follows:

now, the results are as good as the imagination, so how could it be different before? By the way, the whole sequence is changed, and found that no matter how to change the "capture 1" will be printed first, but the event-triggered elements of the capture and bubbling events will vary in order.

This shows: the event flow is really first captured by the outside, in the outward bubbling, triggering the element is different, the trigger element is the target element of the event, then its capture and trigger, that is, according to the order of event registration different to Execute.

Talk about the flow of events, and then the event triggered it.

An event is an action that is performed by the user or the browser itself. such as click,load and mouseover, is the name of the event, and in response to an event execution of the function is the event handler, then how to do the event binding, in fact, there is already,

(1), Execute addeventlistener (' click ', function () {}, false), which means that a click event is registered .

(2), use onclick= "yourfunction ()" in HTML tags This is the most common way.

If you find that AddEventListener is not registered in ie, this is because IE needs to use attachevent (' onclick ', function () {}) to bind events

(3) The event is removed using RemoveEventListener or DetachEvent.

Now that we know how to bind an event to an element, what does it include in triggering the event object?

Event Type

UI events, Focus events, Mouse events, wheel events, text events, keyboard events, composition events, change events, change name Events. Temporarily do not do a detailed summary, next time to improve ...

Memory and performance

In the JS world, each function is an object, consumes memory, and the more objects in memory, the worse the Performance. second, You must specify the number of DOM accesses that are caused by all event handlers beforehand , delaying the interaction readiness time of the entire page. In fact, there are some ways to improve performance from the perspective of how to use the good event Program.

The solution to the "too many event handlers " issue is the event Delegate. Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a certain type. For example, theClick event will always bubble to the document Hierarchy. This means that we can specify an onclick event handler for the entire page , without having to add processing events to each Element. Multiple elements Click on the event merge based on event.target.id to determine the processing logic, so that although the code processing function is longer, but the consumption will be lower. If feasible, can you add an event handler in the Document object to handle a particular type of event for the page,

(1),doucument objects are quickly accessible and can be added to a program at any point in the page life cycle (no waiting for domcontentloaded or load events). That is, as long as the clicked element is rendered on the page, the appropriate functionality is immediately available.

(2), It takes less time to set up event handlers on the Page. Adding only one event handler requires fewer DOM applications and takes less Time.

(3), The entire page occupies less memory space, can improve overall performance.

But also to avoid the binding of the function object too large, enough.

Event Simulation

Use JS at any time to trigger a particular event, just like a browser-created event.

DOM Event Simulation is divided into uievents, mouseevents, mutationevents, htmlevents, temporarily do not do a detailed summary, next time to improve ...

okay, Here's The last thing in the summary of Today's events, custom events

An event is an observer's design pattern, a technique of loosely coupled code. An object can publish an event to represent a moment in the Object's life Cycle. Other objects can then observe the object, waiting for these moments to come and respond by running Code.

The observer consists of two classes of objects: the subject and the observer, the subject responsible for publishing the event, and the Observer observing the subject by subscribing to these Events. The event-handling code is that the Observer DOM element is the principal, registering the event to register the callback function (the event handler).

Custom events are useful when there are multiple parts of your code that interact with each other at specific Times. At this point, if each object has a reference to all objects, the entire code is tightly coupled and difficult to maintain, because modifications to an object also affect other Objects. Use custom events to help decouple related objects and keep functionality Isolated. In many cases, the code that triggers the event and the code that listens to the event are completely detached.

A code example is given below

1 functioneventtarget () {2      this. handlers={};3 }4 5Eventtarget.prototype={6 constructor:eventtarget,7AddHandler:function(type,handler) {8         if(typeof  this. handlers[type] = = "undefined"){9              this. handlers[type]=[];Ten         } one          this. Handlers[type].push (handler); a     }, -Fire:function(event) { -         if(!Event.target) { theevent.target= this; -         } -         if( this. handlers[event.type]instanceofArray) { -             varhandlers= this. handlers[event.type]; +              for(vari=0,len=handlers.length;i<len;i++){ - handlers[i][event]; +             } a         } at  -     }, -Removehandler:function(type,handler) { -         if( this. handlers[type]instanceofArray) { -             varhandlers= this. handlers[type]; -              for(vari=0,len=handlers.length;i<len;i++){ in                 if(handlers[i]===Handler) { -                      break; to                 } +             } -Handlers.splice (i,1); the  *         } $     }Panax Notoginseng};
View Code
1 custom events using the Eventtarget type can be used as follows:2 functionhandlemessage (event) {3Alert ("Message received:" +event.message);4 }5 //Create a new object6 vartarget =NewEventtarget ();7 //Add an event handler8Target.addhandler ("message", handlemessage);9 //Triggering EventsTenTarget.fire ({type: "message", message: "Hello world"}); one //to Delete an event handler aTarget.removehandler ("message", handlemessage); - //again, There should be no handler -Target.fire ({type: "message", message: "hello world"});
View Code

To this I understand the event is basically summed up, some parts have not been summed up, there is time to do a detailed summary of the study Later.

Resources:

(1), "JavaScript advanced programming" version 3

(2): Https://www.w3.org/TR/DOM-Level-3-Events/#ui-events-intro

Events in JavaScript

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.