Learning the eighth day (2019-11-21)

Chapter 13 events

  Interaction between JavaScript and HTML is achieved by the event. The event is certain interactions occur instantaneously document or browser window.

One, the incident flow

   It describes the sequence of event stream received from the event page. 

   Events fractions event bubbling stream, the stream event capture, DOM event flow, it is recommended to use event bubbling streams.

Second, the event handler

   Function responding to an event called the event handler (or event listener). The name of the event handler to "on" at the beginning, so the event handler for the click event is onclick, an event handler for the load event is the onload. Designated handler for the event there are several ways:

     1, HTML event handler
     2, DOM0 level event handler
     3, DOM2 level event handler
     4, IE event handlers

Here is the event handler code cross-browser:

1 <html>
2   <head>
3   </head>
4   <body>
5      <input type = "button" id = "myBtn" value="Click Me">
6      <script type="text/javascript" src="myscript.js"></script>
7   </body>
8 </html>
//myscript.js
var EventUtil = {
    addHandler: function(element,type,handler){
        if(element.addEventListener){ //DOM2级方法
            element.addEventListener(type,handler,false);
        }else if(element.attachEvent){ //IE方法
            element.attachEvent("on"+type,handler);
        }else{ //DOM0级方法
            element["on"+type]=handler;
        }
    },
    removeHandler: function(element,type,handler){
        if(element.removeEventListener){
            element.removeEventListener(type,handler,false);
        }else if(element.detachEvent){
            element.detachEvent("on"+type,handler);
        }else{
            element["on"+type] = null;
        }
    }
};

var btn = document.getElementById("myBtn");
var handler1 = function(){
   alert(this.id);
}
var handler2 = function(){
   alert("hello world!");
}
//btn.addEventListener("click",handler1,false);
//btn.addEventListener("click",handler2,false);
//btn.removeEventListener("click",handler2,false);
EventUtil.addHandler(btn,"click",handler1);
EventUtil.addHandler(btn,"click",handler2);
EventUtil.removeHandler(btn,"click",handler2);

 

Third, the event object 

  When an event is triggered on the DOM, will generate an event object event, this object contains all the information related to the event in. Including the lead elements of the event, type of event, and other information related to a specific event.

  IE and the DOM event object in different, but may be based on the similarity between them is given by the cross-browser scheme. 

Here is the code:

   Can be enhanced front EventUtil objects, add a number of ways.

 1 var EventUtil = {
 2     addHandler: function(element,type,handler){
 3         if(element.addEventListener){
 4             element.addEventListener(type,handler,false);
 5         }else if(element.attachEvent){
 6             element.attachEvent("on"+type,handler);
 7         }else{
 8             element["on"+type]=handler;
 9         }
10     },
11     removeHandler: function(element,type,handler){
12         if(element.removeEventListener){
13             element.removeEventListene(type,handler,false);
14         }else if(element.detachEvent){
15             element.detachEvent("on"+type,handler);
16         }else{
17             element["on"+type] = null;
18         }
19     },
20     getEvent : function(event){
21         return event ? event : window.event;
22     },
23     getTarget:function(event){
24         return event.target||event.srcElement;
25     },
26     preventDefault:function(event){
27         if(event.preventDefault){
28             event.preventDefault();
29         }else{
30             event.returnValue=false;
31         }
32     },
33     stopPropagation:function(event){
34         if(event.stopPropagation){
35              that event.stopPropagation ();
 36          } the else {
 37 [              event.cancelBubble = to true ;
 38 is          }
 39      }
 40  };
 41 is  
42 is  var BTN = document.getElementById ( "myBtn" );
 43 is  
44 is btn.onclick = function (Event) {
 45      Alert ( "Clicked" );
 46      event = EventUtil.getEvent (event); // cross-browser event get 
47      var target = EventUtil.getTarget (event); // returns the event's target 
48     Alert (target === document.body); // false 
49      Alert (=== target the this ); // to true 
50      EventUtil.preventDefault (Event); // cancel the default behavior of the event 
51      EventUtil.stopPropagation (Event); // cancel event bubbling 
52 }

 

Fourth, the event type

 Event Web browser that can occur there are many types. As described above, different types have different event information, "the DOM3 Level Event" provides the following types of events:

       1, UI event fires when interacting with elements on the user page;
       2, focus events triggered when the element gains or loses the focus;
       3, a mouse event is triggered when a user performs an operation on a page with a mouse;
       4, rollers event triggered when a mouse wheel (or similar device);
       5, text event trigger when the input text in the document;
       6, keyboard events, triggered when a user performs an operation on the page through the keyboard; 
       7, synthetic event, when the trigger is IME (input method editor, input method editor) inputting a character;
       8, variation (mutation) event is triggered when the underlying DOM structure is changed.

In addition, HTML5 also defines a set of events, and some browsers will implement other proprietary DOM and events in the BOM. These exclusive events are generally tailored according to the needs of developers, there is no standard, thus achieving different browsers may not match.     

 

Fifth, memory and performance 

    In JavaScript, added to the number of event handlers on the page will be directly related to the overall operating performance of the page. The cause of this problem is multi-faceted. First, each function is an object, takes up memory; the more memory objects, the worse the performance. Secondly, it is necessary to specify in advance all event handlers DOM resulting from the number of visits, interaction will be ready delay time the entire page.  

  1, event delegates

      On the "event handler too" solution to the problem is the event delegate.   

     In the following HTML code as an example

1 <ul id = "myLinks">
2     <li id = "goSomewhere">Go somewhere</li>
3     <li id = "doSomething">Do something</li>
4     <li id = "sayHi">Say hi</li>
5 </ul>
6 <script type="text/javascript" src="myscript.js"></script>

According to the traditional approach, you need to add 3 event handlers for them, and use event delegation, add an event handler on only in the DOM tree as high as possible level, this technique requires less memory footprint and better performance ,code show as below:

 1 var list = document.getElementById("myLinks");
 2 
 3 EventUtil.addHandler(list,"click",function(event){
 4     event = EventUtil.getEvent(event);
 5     var target = EventUtil.getTarget(event);
 6     switch(target.id){
 7         case "doSomething":
 8             document.title="I changed the document's title";
 9             break;
10         case "goSomewhere":
11             location.href="http://www.wrox.com";
12             break;
13         case "sayHi":
14             alert("hi");
15             break;
16     }
17 });

2, remove event handlers

    When not required to remove the event handler can also improve the performance of the page. In memory of those left "empty event handler" obsolete unused, it is the main cause of Web application memory and performance problems. 

    In both cases, it may cause the above problem:

     a, the first case is to remove the element with an event handler when from the document. 

     b, when unloading the page, if not clean up event handler before the page is unloaded, that they will remain in the memory. In general, it is good practice before the page is unloaded, first remove all event handlers by onunload event handler.

 

VI simulated event

     Often triggered by events or user actions by other browser functions. You can also use JavaScript to trigger specific events at any time, at a time when events like the browser to create an event of the same. In other words, these events will bubble up the bubble, and still can lead to process their event handlers browser execution has been specified.

     In testing Web applications, analog trigger event is an extremely useful technique. DOM2-level specification provides for this purpose simulate a specific event, IE9, Opera, Firefox, Chrome and Safari are supported in this way. IE has its own way to simulate events. 

 

 

Guess you like

Origin www.cnblogs.com/xiaoxb17/p/11909230.html