Javascript event flow and event binding _javascript tips

Source: Internet
Author: User
Tags event listener tagname

Event Flow

The flow of events in the browser means that there can be more than one or even multiple elements on the page that respond to the same event. The order in which one or more elements respond to events is different in each browser, primarily for IE and Netscape.

Bubble type event (dubbed bubbling)

The solution on IE is the bubbling event (dubbed bubbling). The basic idea of bubbling events is that events are triggered in the order from the most specific event target to the least specific event target (Document object).

Example (1): Click me to trigger the bubbling flow of events

The XHTML code structure for example (1):

<span id="cnt0">
     <a href=”#1″ id=”link0″>点击我触发冒泡型事件流</a>
</span>

In this example I also tied the click event to span and a tag, and we saw that we clicked on the a tag and clicked (click) and triggered two elements a and span events. The first trigger is the Click event that is bound to the a label, and then the click event for the span label is triggered. That is, the previous mentioned " page can have not only one, or even multiple elements responding to the same event " and " events are triggered in the order from the most specific event target to the least specific event target (Document object) ."

The first target we clicked on in this example is the A-tag link, which is the " most specific event target " mentioned earlier, and then the relative " no specific event target " span. Looking at my XHTML code structure, you'll notice that the a tag is included in the span tag, which means that span is the parent of the a tag, and if it's not clear how they relate, let's look at the following structure of the DOM tree:

The sequence of event triggers is to trigger the Click event up and down the DOM tree from the most specific target, just as a bubble bubbles from the bottom up. "Bubble Type" is that way, but also very image. The point here is that since I only bind click events to A and span, the "run" to span is the top, and if you also have the P tag containing them and the document binding click event, the bubbling process continues until the event trigger in document is finished.

Also, it is possible to support HTML nodes in the top-level DOM node bubbling in IE5.5 as document,ie6. The Mozllia1.0 and later versions also support bubbling, and it is more able to take the window object.

Capture Events (event capturing)

The relative ie4.0,netscape4.0 uses the solution of the capture event. The event triggers a process that is exactly the opposite of bubbling--in a capture event, the event fires from the most imprecise object (the Document object) and then to the most accurate object. Or the previous example, but now it's triggered by a catch event (you need to test in Netscape or Firefox, of course).

Example (2): Click me to trigger the capture-type event stream

The XHTML code structure for example (2):

<span id="cnt1">
     <a href=”#1″ id=”link1″>点击我触发捕获型事件流</a>
</span>

The sequence of events triggers is exactly the opposite of the bubble in front, and I don't go into it.

DOM Event Stream

This event stream is a standard specification for the consortium, which supports both event flow patterns, but captures the event stream first and bubbles the flow of the event.

The most unique of DOM event streams is that it supports text nodes and triggers events (this is not supported in IE). But to tell you the truth, I don't see how it works with text nodes supporting events.

Finally, according to our recent practice in the development of the use of the process, we generally take bubble-type event flow trigger, which we are more successful ie. As for the reason, I think you can see from the above explanation that after all we give the element an event, it's definitely a wish to start with the one we want to trigger first (from the most precise). And the first capture of the DOM bubbles I think can only be used to make me very confused to describe my feelings. Because if you follow the DOM event stream, our events are triggered 2 times, and we generally only choose one type of event flow, the value wants to trigger once, it is difficult to understand what the original world of the world? A word--halo! Maybe my understanding is limited, but this is my true feeling.

Event handler function/Listener function

Here I do not want to do too much introduction, we know in IE use attachevent ("Name_of_event_handler", Fnhandler) to the element binding event, and in the browser that supports DOM event flow, use AddEventListener ("Name_of_event_handler", Fnhandler, Iscapture). Before I control Firefox, triggering the capture event stream is done by setting Iscapture (ture: Capture; false: bubbling). There is our traditional element.onclick or element[' on ' +eventname], which is an event-bound listener supported by all browsers, and I tested the results of XP ie6~8, firefox2.0~3.5, Safari4.0, Opera9.6.4, and Chrome2.0.180 are all triggered by bubbling event streams. Older browsers I have not tested, but according to the Pro Javascript techniques, old browsers use event bindings such as onclick, triggering a bubbling event stream. If you are interested in finding out about the antique browsers, test them. But there are still some events that don't support bubbling, let's talk about it.

Those events are supported bubbling, those not supported?

This is more interesting, the summary here from PPK in Yahoo's speech "Javascript Event" (recommended that you must see, very classic!) To simply summarize the content of PPK, basically only the onload, unload, focus, blur, submit, and change events do not support bubbling, which is what I said earlier, "generally use bubbling event streams." Nature to KeyDown, KeyPress, KeyUp, click, Dbclick, MouseDown, Mouseout, MouseOver, MouseUp, MouseMove. In PPK's words, that is "Mouse and Key events" to support bubbling, and interface events (that is, the HTML (HTML is to build interface) event in the JavaScript advanced programming. Only captures are supported.

Again, he said, click is the "safest" event, which supports bubbling and supports capture. Mouse events can trigger click, and keyboard events can trigger click. Also, in browsers that support DOM events, focus and blur only support capture, so if you use the Addevent function given below, bcapture must set to True if you are binding the focus or blur event to an element. So here is a problem, IE is not supported by the capture, it is not trigger this event? Oh, is a serious problem? However, when using focus and blur events in IE, the trigger is IE focusin and focusout, of course, these two events are only to support bubbling.

PPK said so, but I still want to practice, so I am here to deal with, Window.onfocus = function () {alert (' OK ')},lnkone.onfocus = Democlick; Funny Thing happened! In IE6, when you click on my first example link, hehe, depending on the bubble is over and captured, in the IE8 is only bubbling, but this is only when you click this link occurred. Then I was tentatively "inadvertently" test, click on other applications, another let me unexpected situation happened, actually triggered the window.onfocus, and then triggered the lnk.onfocus!! So I immediately tested the IE6, the same! Depending on IE also "crazy" A, triggering the capture of onfocus Oh, haha!!! Does IE also support capture, ie also crazy???!!!! Or is there another explanation for this phenomenon? Doubts!?!?!! Oh, at first I really think so, let me surprise a, but think carefully, but the sequence of events in order to cause such a false impression.

Oh, the original in the IE6, click on the link, first triggered the onfocus, pop-up hint ' A ', and then close the Pop-up prompt box window, the window has gained focus, and triggered the window focus events. Then the click event that triggers the a tag, and then closes the pop-up prompt window, gives the window the focus, and then the a tag gets the focus. The IE8 test is correct, when the click event is triggered, and then the prompt window is closed, it does not trigger the window focus. Hey! Empty happy A, I also thought that Windows IE support capture it!! But it is not completely no harvest, if you also like me so the whole, you have to pay attention to IE6 will toss two times, but only when you click on it will be so, if you use the tab switch to get focus, will only trigger a label focused event.

Also in Firefox (I test the latest 3.5), but do not window.onfocus, or you will die! I am sorry to use Firefox to see this post of the person, OK a few times, you hung up!! Oh!!!

What is ' this '?

ie in front gave me "surprise", this also give me a surprise. Of course, I didn't notice it before, but Yahoo's engineers found out earlier. This keyword is determined by context, and in the functional function of our event bindings, this should point to the current element node object, which should be a element object. I think this should be a good understanding:

Sample code:


<span id="cnt0">
     <a href=”#1″ id=”link0″>点击我触发捕获型事件流</a>
</span>

<script type=”text/javascript”>
var link = document.getElementById('link1′);
     link.onclick = function(){
          alert(this.tagName);
     };
</script>

This code is officially my way in the example (1), in the example, this points to the a tag this element object, so we can get the TagName this attribute ' a ' of the A tag. Example (2), I use a compatible event listener function:


function addListener(el, event, fn, bCapture){
  var isCapture = bCapture ? bCapture : false;
  try {
    el.addEventListener(event, fn, isCapture);
  }
  catch (e) {
    try {
      el.attachEvent('on' + event, fn);
    }
    catch (e) {
      el['on' + event] = fn;
    }
  }
}

In our browsers that support the DOM event stream, we can also get the correct hint this.tagname as ' A '. This problem is in IE, when we use attachevent to bind an event to an element, now you click on the link below:

Example (3): What is ' this '?

Sample code:
<span id= "cnt2″>
<a href= "#1 ″id=" Link2″>what is ' this '?</a>
</span>

function Whatisthis () {
if (this = = window) {
Alert (' This is a Window object ');
}
Alert (' So, this.tagname are: ' + ' + this.tagname + '. ');
}

<script type= "Text/javascript" >
var cntthree = document.getElementById (' cnt2′), Lnkthree = document.getElementById (' link2′ ');

AddListener (Lnkthree, ' click ', Whatisthis);
AddListener (Cntthree, ' click ', Whatisthis);
</script>

Do you see it clearly? If you are testing in ie6~8, then you point to the Window object rather than a label A. Faint!!! -_-! So you have to be careful, the problem is more ah, to solve the This keyword problem, I give you the suggestion is that you can consider directly with the traditional ' onclick ' or modify the previous binding event listening to the function:

Modified code:

function addEvent(el, event, fn, obj, overrideContext, bCapture){
  var context = el, isCapture = bCapture ? bCapture : false, wrappedFn = null;

  if (overrideContext) {
    if (overrideContext === true) {
      context = obj;
    }
    else {
      context = overrideContext;
    }
  }
  wrappedFn = function(){
    return fn.call(context);
  };
  try {
    el.addEventListener(event, wrappedFn, isCapture);
  }
  catch (e) {
    try {
      el.attachEvent('on' + event, wrappedFn);
    }
    catch (e) {
      el['on' + event] = wrappedFn;
    }
  }
}

Example (4): a little bit more of me, and see what I ' this ' is?

Okay so much, do not know if there is no help to you, the final note, some of the views in this article refer to the "JavaScript Advanced Program Design" (A very good book, recommend everyone to see!) ), addevent function for reference YUI2.7 _addlistener method, here also want to thank Yui those cattle, salute to them!

Static page access address: http://img.jb51.net/online/jsevent/event.htm (if you also want to experience my "surprise", please use IE6 Access, click on the first example link, but do not use Firefox, or you will hang up, Don't say I didn't warn you,!!!. )

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.