Javascript event stream and event binding

Source: Internet
Author: User
ArticleDirectory
    • Dubbed bubbling)
    • Event capturing)
    • DOM event stream
    • Which events Support bubbling and which events do not?
    • What is 'easy '?

Event stream

The event stream in the browser means that there may be one or more elements on the page to respond to the same event. The order in which one or more elements respond to events varies with browsers (mainly for IE and Netscape.

Dubbed bubbling)

The solution on IE is the dubbed bubbling ). The basic idea of a bubble event is that an event is triggered in sequence from the most specific event target to the least specific event Target (Document Object.

Example (1 ):Click to trigger a bubble event stream

Example (1) XHTMLCodeStructure:

<Span id = "cnt0">
<A href = "#1" id = "link0"> click I to trigger a bubble event stream </a>
</Span>

In this example, I bound a click event to the span and a tags at the same time. As you can see, We click this a tag and click it once) two elements a and span are triggered at the same time. The first trigger is the Click Event bound to the tag, and then the Click Event of the span tag. That is, the"There may be one or more elements on the page to respond to the same eventAndEvents are triggered in the order from the most specific event target to the least specific event Target (Document Object ).".

In this example, the first target we click is the tag link, which is the"The most specific event Target", And then the relative" span"Unspecified event targets". Looking at the XHTML code structure, you will find that the tag is contained in the span tag, that is, the span is the parent node of the tag. If you do not know the relationship between them clearly, let's take a look at the structure of the DOM tree below:

The sequence of event triggering is to continuously trigger click events from the most specific target along the DOM tree, just like the process where bubbles keep popping up from the bottom."Bubble"That is, the image obtained is also very good. It should be noted that, because I only bound a and span with a click event, the "pop" to the top of the span will be reached, if you also bind a click event to the P tag containing them and the document, the Bubbling Process will continue until the event triggering of the document ends.

In ie5.5, the top Dom node of bubble is document, and in IE6, HTML nodes are supported. In mozllia1.0 and later versions, bubble is also supported, and it can be used to expose window objects.

Event capturing)

Compared with ie4.0, netscape4.0 uses the capture event solution. The trigger process of this event is exactly the opposite of the bubble-in a capture event, the event is triggered from the most inaccurate object (Document Object), and then to the most precise object. It is still the previous example, but now it is triggered by a capture event (of course you need to test it in Netscape or Firefox ).

Example (2 ):Click "I trigger the capture event stream ".

Example (2) XHTML code structure:

<Span id = "cnt1">
<A href = "#1" id = "link1"> click I trigger the capture event stream. </a>
</Span>

The sequence triggered by the event is the opposite of the bubble above. I will not go into details here.

DOM event stream

This event stream is a standard specification developed by W3C. It supports two event stream modes at the same time, but only a capture event stream occurs before a bubble event stream occurs.

The most unique thing about DOM Event streams is that it supports text nodes and triggers events (not supported in IE ). But to be honest, I still cannot see what role it plays to allow the event support for text nodes.

Finally, according to our recent application in the development practice, we generally adopt the event stream Triggering Method of the bubble type. This is a relatively successful practice of IE. As for the reason, I think you can see from the above explanation that, after all, we certainly want to trigger events for elements from the one we most want to trigger first (from the most accurate. The first capture and then bubbling of Dom can only be used to describe how I feel. Because if we trigger an event twice according to the DOM event stream, we generally select only one type of event stream, and the value is expected to be triggered once, it's hard to understand what W3C thought at the beginning ?! One word-dizzy! Maybe my understanding is limited, but this is what I really feel.

Event processing function/listener Function

I don't want to introduce it too much here. We know that it is used in IE.Attachevent ("name_of_event_handler", fnhandler)Bind events to elements. In browsers that support DOM Event streams, useAddeventlistener ("name_of_event_handler", fnhandler, iscapture). Previously, I used Firefox to trigger capture event streams by setting iscapture (Ture: capture; false: Bubble. There is also our traditional element. onclick or element ['on' + eventname]. This is the event binding listener supported by all browsers, and the result of my test is IE6 ~ in XP ~ 8. firefox2.0 ~ 3.5, safari4.0, opera9.6.4, and chrome2.0.180 are all triggered by a bubble event stream. I have never tested the older browser, but according to "Pro JavaScript techniques", the old browser uses event binding such as onclick to trigger a bubble event stream. If you are interested, find out the antique browsers and test them. But there are still events that do not support bubbling. Let's talk about it below.

Which events Support bubbling and which events do not?

This is quite interesting. The summary here comes from PPK's speech "javascript event" at Yahoo (we recommend you take a look at it, which is classic !), Summary of PPK content, basically only onload, unload, focus, blur, submit, and change events do not support bubbling."Bubble event stream is generally used". Naturally To keydown, keypress, keyup, click, dbclick, mousedown, mouseout, Mouseover, mouseup, mousemove. In PPK, "Mouse and key events" supports bubbling, and interface events (that is, JavaScript advancedProgramHTML (HTML is used to build interfaces) Events in design .) Only capture is supported.

He said again: click is"Safest"Event, which supports both bubble and capture. Mouse events can trigger click, and Keyboard Events can also trigger click. Also, in browsers that support DOM events, focus and blur only support capturing. If you use the addevent function provided below, when binding a focus event to an element or a blur event, bcapture must be set to true. So there is a problem here. ie does not support capturing. Isn't it possible to trigger this connection event? Oh, it's a serious problem? However, when the focus and blur events are used in IE, The focusin and focusout events of IE are actually triggered. Of course, these two events only support bubbling.

Although PPK said so, I still want to practice it, so I have handled it here, window. onfocus = function () {alert ('OK')}, lnkone. onfocus = democlick; interesting thing happened! In IE6, When you click my first example link, you can see that the bubble is complete and captured. In IE8, the bubble is only found, however, this only happens when you click this link. Then I tested it tentatively and clicked on other applications. Another unexpected situation happened to me, and the window was triggered first. onfocus, then the Lnk is triggered. onfocus !! So I immediately tested IE6, the same! IE is also crazy, triggering the onfocus capture. Haha !!! Does ie support capturing, and IE is crazy ???!!!! Or is there any other explanation for this phenomenon ?? Doubt !?!?!! At first, I did think so, which surprised me. But I thought about it carefully, but the reason for the order of event execution gave me the illusion.

In IE6, click the link to trigger the onfocus first, and the prompt 'A' is displayed. Then, when the pop-up prompt box window is closed, the window gets the focus, it also triggers the focus event of the window. Then, the click event of tag a is triggered, and when the pop-up Prompt window is closed, the focus of the window is obtained, and then the focus of tag a is obtained. The IE8 test is correct. When the click event is triggered and the prompt window is closed, the focus of the window is not triggered. Ah! I was so happy that I thought Windows's ie support was captured !! However, it is not completely fruitless. If you are as full as me, you should note that IE6 will be tossing twice, but it will only happen when you click, if you use the tab switch to obtain the focus, only the focus event of tag a is triggered.

In Firefox (the latest 3.5 I tested), do not use window. onfocus. Otherwise you will be down! Sorry, the person who used Firefox to read my post. After several OK times, you will be suspended !! Haha !!!

What is 'easy '?

IE gave me a "surprise" and this also gave me a surprise. Of course, I didn't notice it before, But Yahoo's engineers found it early. This keyword is determined based on context. In the function bound to an event, this should point to the current Element Node object and be an element object. I think you should understand this:

Sample Code:


<Span id = "cnt0">
<A href = "#1" id = "link0"> click I trigger the capture event stream. </a>
</Span>

<SCRIPT type = "text/JavaScript">
VaR link = Document. getelementbyid ('link1 ′);
Link. onclick = function (){
Alert (this. tagname );
};
</SCRIPT>

This code is the processing method in example (1). In this example, this is the Element Object of the tag, so we can get the tagname attribute 'a' of the tag '. In Example (2), I use a compatible event listening 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 browser that supports DOM Event streams, we can also get the Correct prompt that this. tagname is 'A '. This problem occurs in IE. When we use attachevent to bind an event to the element, click the following link:

Example (3 ):What is 'easy '?

Sample Code:
<Span id = "cnt2">
<A href = "#1" id = "link2"> what is 'others '? </A>
</Span>

Function whatisthis (){
If (this = Window ){
Alert ('this is a window object ');
}
Alert ('so, this. tagname is: '+ ''' + this. tagname + ''. ');
}

<SCRIPT type = "text/JavaScript">
VaR cntthree = Document. getelementbyid ('cnt2'), lnkthree = Document. getelementbyid ('link2 ′);

Addlistener (lnkthree, 'click', whatisthis );
Addlistener (cntthree, 'click', whatisthis );
</SCRIPT>

Are you clear? If you are in IE6 ~ Test in 8, then you click the window object instead of a tag. Fainted !!! -_-! So you need to be careful. There are many problems. You need to solve this keyword problem, my advice is that you can use the traditional 'onclick' directly or modify the previously bound event listening 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 ):Click me again to see what my 'eas' is?

Well, that's all. I don't know if it is helpful to you. Finally, I 'd like to explain that some of the points in this Article refer to JavaScript advanced programming (a good book, I suggest you read it !), The addevent function draws on the _ addlistener method of yui2.7. Here, I would like to thank the Yui cool people and pay tribute to them!

static page access address: http://img.jb51.net/online/jsevent/event.htm (if you also want to experience my "surprise", please access with IE6, click the first example link, but never use Firefox, otherwise, it will fail. Don't say I didn't remind you !!!)

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.