[Translation] JavaScript event Learning Chapter 8: sequence of events

Source: Internet
Author: User
Document directory
  • Assume that you write
  • Compatibility in traditional mode
  • It always happens
  • Use
  • Turn it off
  • Currenttarget
  • Microsoft Models

In the first chapter, I mentioned a problem that may not seem so understandable for the first time: "If an element and its parent element have an event handler for the same event, which of the following statements will be executed first?" There is no doubt what browser it is.

The basic problem is simple. Assume that one of your elements is included in another element.

-----------------------------------
| element1 |
| ------------------------- |
| |element2 | |
| ------------------------- |
| |
-----------------------------------

Both elements have an onclick event handler. If you click on element2, the click event is triggered on both element 2 and element 1. But which event occurs first? Which event processing program will be executed first? In other words, what is event order?

 

Two modes

Without a doubt, Netscape and Microsoft have made their own decisions in the bad days of the past.
Netscape said element1 first occurred. This is called event capturing ).
Microsoft thinks element2 happened first. This is called event bubbling ).
The two events are in the opposite order. IE only supports event bubbling. Mozilla, opera 7, and Konqueror are supported. Earlier opear and ICAB browsers are not supported.

Event capture

When you use event capture

               | |
---------------| |-----------------
| element1 | | |
| --------- --| |----------- |
| |element2 \ / | |
| ------------------------- |
| Event CAPTURING |
-----------------------------------


The event handler of element1 is executed first, and element2 is executed later.

 

Event bubbling

But when you use event bubbling

               / \
---------------| |-----------------
| element1 | | |
| ---------- -| |----------- |
| |element2 | | | |
| ------------------------- |
| Event BUBBLING |
-----------------------------------


The event handler of element2 is executed first, and the event handler of element1 is executed later.

 

W3C Mode

W3C decided to maintain gravity in this war. In the W3C event model, any event is first captured until the target element is reached, and then bubbling.

                        | |  / \
-----------------| |--| |-----------------
| element1 | | | | |
| ----------- --| |--| |----------- |
| |element2 \ / | | | |
| -------------------------------- |
| W3C event model |
------------------------------------------

As a designer, you can register the event handler in the capture or bubble phase at will. You can use the addeventlistener () method described in advanced mode. If the last parameter is true, it is set to event capture. If it is false, it is set to event bubble.

 

Assume that you write

 

element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)


If you click element2, the following occurs:
1. Click events occur in the capture phase. In this case, if any parent element of element2 has an onclick event handler, It will be executed.
2. If dosomething2 () is found on element1, It will be executed.
3. Events are passed down until the target itself, and there are no other capture phase programs. The event then enters the bubble stage and then executes dosomething (), that is, element2 registers the event handler in the bubble stage.
4. The event is passed up and then checked whether there is a parent element to set the event handler in the bubble stage. No, so nothing will happen.

Reverse:

element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)

Now, if you click element2, the following occurs:
1. Event click occurs in the capture phase. The event will check whether the parent element of element2 registers the event handler during the capture phase, which is not found here.
2. Events are passed down until the target itself. Then start the bubble stage and execute dosomething (). This is the event handler registered in the element2 bubble stage.
3. The event continues to be passed up and then checks whether the event handler has been registered in the bubble stage.
4. element1. then dosomething2 () is executed.

 

Compatibility in traditional mode

For browsers that support W3C Dom, traditional event registration

element1.onclick = doSomething2;


It is regarded as registration in the bubble stage.

 

Use of event bubbling

Few designers are aware of event capture or bubbling. Today, when creating webpages, it seems that there is no need to let a bubble event be handled by a series of event handlers. Users will also be confused when a series of events occur after clicking. Generally, you also want to keep the code of your event handler independent. When a user clicks an element, something happens. When the user clicks another element, other things happen again.

Of course, it may change in the future. It is best to make the mode forward compatible. However, the most practical event capture and bubbling are registration of default functions.

It always happens

First, you need to understand that event capture or bubbling is always happening. If you define an onclick event for your entire page:

document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);


The click Time on any element will bubble to the page and start the event handler. Only the current event handler explicitly blocks bubbles will not be passed to the entire page.

 

Use

Because every event is stopped throughout the document, the default event handler becomes possible. Suppose you have a page like this:

------------------------------------
| document |
| --------------- ------------ |
| | element1 | | element2 | |
| --------------- ------------ |
| |
------------------------------------

element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;

Now, if you click element1 or element2, dosomething () is executed. If you want to, you can also stop the spread. If not, defaultfunction () is executed. Click defaultfunction () elsewhere. Sometimes this may be useful.

It is necessary to set a global event handler when writing and dragging code. Generally, the mousedow event on a layer selects this layer and then responds to the mousemove event. Although mousedown is usually registered at this layer to avoid browser bugs, other Event Handlers must be global (document-wide ).

Remember the first law of browser logic: everything will happen, and it is often when you have the least preparation. What may happen is that the user's mouse moves wildly and the Code does not keep up with it. As a result, the mouse is no longer on this layer.

 

  • If the onmousemove event handler is registered on a layer and the layer does not respond to the mouse movement, the user will be confused.
  • If an onmouseup event handler is registered, the program does not capture the layer when the user releases the mouse.

In this case, event bubbling is very important, because the global event handler will guarantee the execution.

Turn it off

However, you usually want to disable all related capture and bubbles. In addition, if your document structure is very complex (such as a large number of complex tables), you also need to disable bubbling to save system resources. Otherwise, the browser needs to check whether the parent element has an event handler. Although none of them may exist, searching is a waste of time.

In Microsoft mode, you must set the cancelbubble attribute of the event to true.
Window. event. cancelbubble = true
In W3C mode, you must call the stoppropagation () method.

e.stopPropagation()


This will block the event's bubble phase. Blocking event capture is basically impossible. I want to know why.

A complete cross-browser code is as follows:

function doSomething(e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}

Setting in a browser that does not support cancelbubble is not a problem. The browser creates such an attribute. Of course it is useless, just for security.

 

Currenttarget

As we have mentioned before, an event contains a reference of the target or srcelement element in which an event occurs. In our example, element2 is used because the user clicks him.

It is important to understand that this target will not change during the capture and bubble process: it always points to element2.

But suppose we have registered the following event handler:

element1.onclick = doSomething;
element2.onclick = doSomething;


If you click element2, dosomething () is executed twice. How do you know that the HTML element handles this event? Target/screlement cannot give an answer either. It has been pointing to element2.

To solve this problem, W3C added the currenttarget attribute. It contains a reference to the HTML element of an event being processed: the one we want. Unfortunately, the Microsoft mode does not have similar attributes.

You can also use the this keyword. In this example, the HTML element pointing to the event being processed is currenttarget first.

 

Microsoft Models

However, when you use Microsoft's event registration model, the this keyword is not just for HTML elements. There is no property similar to currenttarget, which means that if you do this:

element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)


You don't know that the HTML element is processing the event. This is the most serious problem with Microsoft's event registration model, so we should not use it at all, even those programs that are only under IE/win.

I hope Microsoft can add a property similar to currenttarget or follow the standard as soon as possible? Our design is in urgent need.

 

Continue

If you want to continue learning, please refer to the next chapter.

Address: http://www.quirksmode.org/js/events_order.html
My Twitter: @ rehawk

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.