Overview of js custom events and event interaction principles (2)

Source: Internet
Author: User

Js custom events (1) are designed to give you a simple understanding of how custom events are simulated. It is not difficult to find many defects, such:
1. This event object can only register one event and cannot provide multiple events
2. No information is returned for the registration method.

Next we will solve these problems. The following is the source code of MyEvent. js:
Copy codeThe Code is as follows:
Function MyEvent (){
This. handlers = {};
}
MyEvent. prototype = {
AddHandler: function (type, handler)
{
If (typeof this. handlers [type] = "undefined ")
{
This. handlers [type] = [];
}
This. handlers [type]. push (handler );
},
Fire: function (event)
{If (this. handlers [event. type] instanceof Array)
{
Var handlers = this. handlers [event. type];
For (var I = 0, len = handlers. length; I <len; I ++)
{
Handlers [I] (event );
}
}
},
RemoveHandler: function (type, handler)
{
If (this. handlers [type] instanceof Array)
{
Var handlers = this. handlers [type];
For (var I = 0, len = handlers. length; I <len; I ++)
{
If (handlers [I] === handler)
{
Break;
}
}
Handlers. splice (I, 1 );
}
}
};

This is the optimization of the first article.
The property handler is changed to handlers and an array.
The addHandler () method accepts two parameters: the event type and the function used to process the event. When this method is called, a check is performed to check whether an array for this event type already exists in the handlers attribute.
If not, a new one is created. Then, use push () to add the handler to the end of the array.

The fire () method is used to trigger an event. This method accepts a parameter and is an object containing at least the type attribute. Otherwise, it cannot determine whether the handlers already exists. It will use this type to find a group of handlers for the event type, call each function, and provide the event object. Because these are all custom objects, you can define other things in the event object.

The removeHandler () method is used by addHandler (). They accept the same parameters: the event type and event handler. This method searches for the array of Event Handlers to find the location of the handler to be deleted. If yes, use the break operator to exit the loop. Then, use the splice () method to delete the project from the array.

Here we use a long way to use it. Now I know that many products have two ways to use events. One is direct inheritance (js does not have this concept in this province, however, we can use the prototype chain to simulate the inheritance effect. We will not explain it in detail here.) This event object will have these actions, but this method is quite limited, another method is more commonly used, that is, to use the event class to create an attribute to store this object. For example, create another Student. js file under the same sub-directory. The code in the file is as follows:
Copy codeThe Code is as follows:
Function Student (name)
{
This. myEvent = new MyEvent ();
This. name = name;
}
Student. prototype = {
SetName: function (name)
{
Var eventStart = {
Type: "changeNameStart ",
NewName: name,
OldName: this. name
};
This. myEvent. fire (eventStart );
This. name = name;
}
}

Here is a student class. The constructor initializes a MyEvent object as the property and uses the parameter to initialize the name property.

The setName method is provided to change the name, but a listener that may trigger the event changNameStart is set before the name is changed.
Create an html page and place it in the same directory. The Code is as follows:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> </title>
<Script type = "text/javascript" src = "MyEvent. js"> </script>
<Script type = "text/javascript" src = "Student. js"> </script>
<Script type = "text/javascript">
Function init ()
{
// Initialize a student object
Var student = new Student ("Mr liu ");
// Register the event changNameStart
Student. myEvent. addHandler ("changeNameStart", myMethod );
// Set name to trigger the event changNameStart
Student. setName ("Mr Huang ");
}
Function myMethod (e)
{
Alert ("Event type:" + e. type + "; change the previous name:" + e. oldName + "; changed name:" + e. newName );
}
</Script>
</Head>
<Body>
<Input type = "button" onclick = "init ()" value = "test"/>
</Body>
</Html>

This makes it easy to use and is also a commonly used method.
We also need to make some optimizations when using events in real projects, such:
1. the user does not know what events we provide. From the code, it seems that all events can be added to handlers, but the actual effect (where we set the fire () method) events cannot be intuitively Viewed from the code. Generally, they are used as products and need to be considered in this respect.

2. Have you found that the fire parameter event does not seem to be fixed? In the Daxing project, it is best to make the event a type, which is easier to use in the fire area, there may be many types of events, and some judgments may appear in the fire at that time.
We hope to help readers of the initial js events and communicate with each other.

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.