Chapter 4 traditional event registration model _ javascript skills

Source: Internet
Author: User
In this chapter, I will explain the best way to register events for elements, that is, to ensure that a specific event occurs on a specific HTML element and can run a specific script. Registering events in the oldest JavaScript browser can only pass the inline mode. Since DHTML fundamentally changes the method of page operations, event registration must be scalable and adaptable. Therefore, a corresponding event model is required. Netscape started in the third-generation browser, and IE started in the fourth-generation browser.
Because Netscape 3 began to support this new event registration model, which was a de facto standard before the browser war. So Microsoft had to make the last concession on compatibility for the countless pages on the Internet that used the Netscape event processing model.
These two browsers actually support the following code:

The Code is as follows:


Element. onclick = doSomething;


This is the best way to register an event. No matter when the user clicks this HTML element, doSomething () will be executed. This is the only best way to register events that can be viewed across pages. It is also important to have a deep understanding of this model and its limitations.
Because there is no official standard, I am now referred to as the traditional event registration model (traditional event registration model ). At the same time, w3c has standardized event registration, and Microsoft has also released an advanced mode, but the traditional mode can still run well.


Advanced event registration program
Beginning with Netscape 3/IE 4, JavaScript can recognize the attributes of a series of events on elements. Most HTML elements have attributes such as onclick, onmouseover, and onkeypress. The attributes of those elements-the events supported by those elements-depend on the browser.
These attributes are nothing new to them. It already exists in the oldest JavaScript browser.

The Code is as follows:





Here, the tag has an onclick parameter, which becomes an attribute of element A in JavaScript. The event handlers of old browsers can only be registered by setting element parameters in the source code of the page. If you want to run this script on all the tags, you need to add the onclick event to all the links.
With the arrival of the traditional event registration model, The onclick, onmouseover, or other event processing of HTML elements can all be registered through JavaScript. Now you can add, modify, or delete some event handlers without having to touch the HTML. When you access HTML elements through DOM, you can write code like the following:

The Code is as follows:


Element. onclick = doSomething;



Now our example function doSomething () is registered on the onclick attribute of the element, and will be executed when the user clicks this element function. Note that the event names must be in lower case.
To delete this event handler, simply leave the Click Event empty:

The Code is as follows:


Element. onclick = null;


The event handler is the same as a common JavaScript function. It can be executed even if the event does not occur. If you write it like this:

The Code is as follows:


Element. onclick ()


Then doSomething will be executed. Although it is a function that does not know what to do or produces an error, there is no real event. Therefore, this method is rarely used to execute event handlers.
Microsoft's IE5.5 and later IE also have a fireEvent () method to accomplish the same thing. Use:

The Code is as follows:


Element. fireEvent ('onclick ')



No brackets
Note that you cannot use parentheses when registering an event handler. The onclick method is set to another function. If you write

The Code is as follows:


Element. onclick = doSomething ();



Then this function will be executed and its results will be registered on onclick. This is not what we expected. We just hope that the function can be executed when an event occurs. In addition, the function is written to execute an event. Otherwise, serious confusion and errors may occur.
So we copy the entire doSomething () method in the event handler. We just want to execute this function when the event is executed.


This
In JavaScript, The this keyword usually refers to the function owner. If this points to the HTML element of the event, everything is so beautiful that you can do a lot of things very easily.
Unfortunately, although this is very powerful, it is still difficult to use it if you do not know exactly how it works. I have a detailed discussion about this in another place. Here I will give some overview in the traditional mode.
In the traditional mode, this works as follows. Note that this is slightly different from the inline mode. Now the this keyword is in the function, not in the HTML parameter. This difference will be discussed later.

The Code is as follows:


Element. onclick = doSomething;
Another_element.onclick = doSomething;
Function doSomething (){
This. style. backgroundColor = '# cc0000 ';
}


If you have registered doSomething () as a click event for any HTML element, the element gets a background when you click that element.


Anonymous functions)
Suppose you want all p to change the background color when the mouse passes, and then return the background color when the mouse leaves. To use this correctly, you can write as follows:

The Code is as follows:


Var x = document. getElementsByTagName ('div ');
For (var I = 0; I X [I]. onmouseover = over;
X [I]. onmouseout = out;
}

Function over (){
This. style. backgroundColor = '# cc0000'
}

Function out (){
This. style. backgroundColor = '# ffff'
}



These codes can be run. No problem. However, since both over () and out () are relatively simple, you can use a more elegant anonymous Function Method to write:

The Code is as follows:


For (var I = 0; I X [I]. onmouseover = function (){
This. style. backgroundColor = '# cc0000 '}
X [I]. onmouseout = function (){
This. style. backgroundColor = '# ffff '}
}


Both onmouseover and onmouseout get a function. Instead of copying over () and out (), it is better to directly define an event handler on the event registration script. Since these functions have no names, they are anonymous functions.
The two methods for registering event handlers are basically the same. The only difference is that the second method has less code. I like Anonymous functions very much and I will use them when registering a simple event handler.


Problem
One small problem is that in traditional mode, The onclick attribute can only contain one function. When you want to register multiple event handlers for an event, the problem arises.
For example, you have written a module that can be dragged. This module is registered on the onclick event handler, so you can click it to start dragging. You also wrote a module to track users' clicks and send messages to the server during onunload, so that you can know how your page is used. This module also needs to register an onclick event on the element.
So it may be like this:

The Code is as follows:


Element. onclick = startDragDrop;
Element. onclick = spyOnUser;


This will cause an error. The second registration program will overwrite the first one. When a user clicks an element, only spyOnUser () is executed.
The solution is to register a method that contains two methods:

The Code is as follows:


Element. onclick = function (){
StartDragDrop ();
SpyOnUser ()
}




Flexible Registration
However, assume that you do not use two modules on every page of your website. If you still write:

The Code is as follows:


Element. onclick = function (){
StartDragDrop ();
SpyOnUser ()
}


You will get an error message because one of the functions is undefined. Therefore, be especially careful when registering events. If we want to register spyOnUser () When startDragDrop () is already registered, we can write as follows:

The Code is as follows:


Var old = (element. onclick )? Element. onclick: function (){};
Element. onclick = function (){
Old ();
SpyOnUser ()
};


First, you define a variable old. If the element already has an onclick event handler, store it into old. If not, set old to an empty function. Now you want to register a new event handler for p. Then the program will first execute old () and then execute spyOnUser (). Now the new event handler is added to the element, and the previously registered (if any) is also included.
Last question: what if you want to remove one of the event handlers? I am not sure yet. You need to edit element. onclick () in some ways. I have not studied this problem.
Other Modes
We can see that the traditional mode is very simple and easy to use, but the solution is ugly when you add several programs to an event. W3C Event Handlers solve this problem well.
Continue
If you want to continue learning, please refer to the next chapter.
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.