Event design overview

Source: Internet
Author: User

Event design overview
The event mechanism makes the program logic more in line with the real world. In JavaScript, many objects have their own events. For example, the button has an onclick event, and the drop-down list box has an onchange event, these events allow easy programming. Can an event mechanism be implemented for a defined class? Yes. Through the event mechanism, classes can be designed as independent modules, and the program development efficiency is improved through event communication. This section describes the event Design Patterns in JavaScript and possible problems.

Simplest event Design Model
The simplest mode is to define a method member of a class as an event. No special syntax is required. It is usually an empty method, for example:
Function class1 (){
// Constructor
}
Class1.prototype = {
Show: function (){
// Implement the show Function
This. onshow (); // triggers the onshow event
},
Onshow: function () {}// defines the event Interface
}
In the code above, a method is defined: Show (), and The onshow () method is called in this method. This onshow () method is an external event interface, the usage is as follows:
// Create a class1 instance
VaR OBJ = new class1 ();
// Create the OBJ onshow event handler
OBJ. onshow = function (){
Alert ("onshow event ");
}
// Call the show method of OBJ
OBJ. Show ();

It can be seen that the obj. onshow method is defined outside the class and called in the show () Internal method of the class, which implements the event mechanism.
The above method is very simple. In actual development, it is often used to solve some simple event functions. It is simple because it has two disadvantages:
? Parameters cannot be passed to the event handler because the event handler is called in the show () Internal method and external parameters cannot be known;
? Each event interface can only bind one event handler, while the internal method can bind multiple handlers using the attachevent or addeventlistener method.
In the following two sections, we will focus on solving this problem.

Passing parameters to the event handler
Passing parameters to the event handler is not only a problem in the Custom event, but also an issue in the event mechanism of the system's internal objects, because the event mechanism only transmits the name of one function, the parameter cannot be passed because it does not contain any parameter information. For example:
// Define class class1
Function class1 (){
// Constructor
}
Class1.prototype = {
Show: function (){
// Implement the show Function
This. onshow (); // triggers the onshow event
},
Onshow: function () {}// defines the event Interface
}
// Create a class1 instance
VaR OBJ = new class1 ();
// Create the OBJ onshow event handler
Function objonshow (username ){
Alert ("hello," + username );
}
// Define the variable Username
VaR username = "Jack ";
// Bind the OBJ onshow event
OBJ. onshow = objonshow; // The username variable cannot be passed in.
// Call the show method of OBJ
OBJ. Show ();
Note that the above obj. onshow = objonshow event binding statement cannot be written to pass the username variable:
OBJ. onshow = objonshow (username );
Or:
OBJ. onshow = "objonshow (username )";
The former assigns the running result of objonshow (username) to OBJ. onshow, while the latter assigns the string "objonshow (username)" to OBJ. onshow.
To solve this problem, we can consider the opposite idea, instead of how to pass the parameter, but how to build an event handler without parameters, this program is created based on the event handler with parameters and is an outer encapsulation. Now you can customize a common function to implement this function:
// Encapsulate a function with parameters as a function without Parameters
Function createfunction (OBJ, strfunc ){
VaR ARGs = []; // defines the parameters that ARGs uses to store the parameters passed to the event handler.
If (! OBJ) OBJ = Window; // if it is a global function, OBJ = window;
// Obtain the parameters passed to the event handler.
For (VAR I = 2; I <arguments. length; I ++) args. Push (arguments [I]);
// Encapsulate the call of the event handler using a non-Parameter Function
Return function (){
OBJ [strfunc]. Apply (OBJ, argS); // pass the parameter to the specified event handler
}
}
This method encapsulates a function with parameters as a function without parameters, which is not only applicable to global functions, but also to functions existing as object methods. This method first receives two parameters: OBJ and strfunc. OBJ indicates the object where the event handler is located; strfunc indicates the name of the event handler. In addition, the program uses the arguments object to process the implicit parameters after the second parameter, that is, the parameters of the undefined form parameter, and these parameters are passed when the event handler is called. For example, an event handler is:
Someobject. eventhandler = function (_ arg1, _ arg2 ){
// Event processing code
}
It should be called:
Createfunction (someobject, "eventhandler", arg1, arg2 );
In this case, a function without parameters is returned, and the parameters passed in are included in the returned function. If a global function is used as an event handler, it is actually a method of the window object, so you can pass the window object as the OBJ parameter. To be clearer, you can also specify OBJ as null, the createfunction function automatically considers the function as a global function and automatically assigns the OBJ value to window. The following is an example of an application:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Encapsulate a function with parameters as a function without Parameters
Function createfunction (OBJ, strfunc ){
VaR ARGs = [];
If (! OBJ) OBJ = window;
For (VAR I = 2; I <arguments. length; I ++) args. Push (arguments [I]);
Return function (){
OBJ [strfunc]. Apply (OBJ, argS );
}
}
// Define class class1
Function class1 (){
// Constructor
}
Class1.prototype = {
Show: function (){
// Implement the show Function
This. onshow (); // triggers the onshow event
},
Onshow: function () {}// defines the event Interface
}
// Create a class1 instance
VaR OBJ = new class1 ();
// Create the OBJ onshow event handler
Function objonshow (username ){
Alert ("hello," + username );
}
// Define the variable Username
VaR username = "Jack ";
// Bind the OBJ onshow event
OBJ. onshow = createfunction (null, "objonshow", username );
// Call the show method of OBJ
OBJ. Show ();
// -->
</SCRIPT>
In this Code, the variable username is passed to the objonshow event handler as a parameter. In fact, the event handler obtained by obj. onshow is not objonshow, but a non-argument function returned by createfunction.
Through createfunction encapsulation, you can use a general solution to implement parameter transfer. This applies not only to custom events, but also to events provided by the system. The principles are identical.


Enable multi-bind for custom events
You can use the attachevent or addeventlistener method to bind multiple Event Handlers without conflict. How can custom events implement multi-subscription? The following describes the implementation. To implement multi-subscription, a mechanism is required to store multiple Bound event handlers and call these Event Handlers when an event occurs. To achieve multi-subscription, the implementation is as follows:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Define class class1
Function class1 (){
// Constructor
}
// Define class members
Class1.prototype = {
Show: function (){
// Show Code
//...

// If an event is bound, the onshow array is cyclically triggered.
If (this. onshow ){
For (VAR I = 0; I <this. onshow. length; I ++ ){
This. onshow [I] (); // call the event handler
}
}
},
Attachonshow: function (_ ehandler ){
If (! This. onshow) This. onshow = []; // use an array to store the Bound event handler reference.
This. onshow. Push (_ ehandler );
}
}
VaR OBJ = new class1 ();
// Event handler 1
Function onshow1 (){
Alert (1 );
}
// Event handler 2
Function onshow2 (){
Alert (2 );
}
// Bind two event handlers
OBJ. attachonshow (onshow1 );
OBJ. attachonshow (onshow2 );
// Call show to trigger the onshow event
OBJ. Show ();
// -->
</SCRIPT>
From the code execution results, we can see that the bound two event handlers have been correctly run. To bind an event handler with parameters, you only need to add the createfunction method, which has been described in the previous section.
This mechanism basically illustrates the basic idea of handling multi-event processing programs, but there is still room for improvement. For example, if a class has multiple events, you can define a method similar to attachevent for unified event binding. If you want to delete the event after adding event binding, you can also define a detachevent method to unbind the event. The basic idea of these implementations is to operate arrays.

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.