How to create custom events in JavaScript

Source: Internet
Author: User
Tags echo message
The foundation of avaScript event processing for all client applications. When an event occurs in a target element, such as Button clicking, mouse moving, and form submission, a handler function is executed. An event object is passed to the handler to provide various attributes and a large number of methods to prevent violations. One drawback is that... SyntaxHighlighter. all (); avaScript the basis for processing all client applications. When an event occurs in a target element, such as Button clicking, mouse moving, and form submission, a handler function is executed. An event object is passed to the handler to provide various attributes and a large number of methods to prevent violations.
One drawback is that the event inevitably matches the DOM element. Consider a simple form that accepts information from users:
 
We can compile a screen for processing the echo message and submit a form, for example.
Document. getElementById ("msgbox"). addEventListener ("submit", function (e ){
E. preventDefault ();
Var msg = e. currentTarget. getElementById ("msg"). value. trim ();
If (msg ){
Alert (msg );
}
}, False );
If we want to send a message as a tweet, it is stored on a server, or execute other behaviors? We have two options:
 
1. Add code to our existing further handler.
This is the rigidity since we need to update and test our handler functions every time we add, change, or delete features. There may be dozens of messages published for usage, and we try to apply them all in the same code block.
2. Create an event handler for each application.
This will lead to maintenance problems caused by more elegant code. First, each function must perform similar actions to extract and verify messages. If we need to change our form? To rename an ID, we need to change the event processing code to every subscriber.
That's not very good. If we can simply improve a custom "newMessage" event every time a valid message is published? It would be even better if we could simply monitor document or body labels instead of referencing a specific form node. This is exactly what custom events allow us to do.
It is easy to increase a custom event. We select a new CustomEvent object by name, details:
Var event = new CustomEvent (
"NewMessage ",
{
Detail :{
Message: "Hello World! ",
Time: new Date (),
},
Bubbles: true,
Cancelable: true
}
);
In this example, "newMessage" is a custom event type. The second parameter indicates that an object has three attributes:
Details: A child object provides custom event information. In this example, a message and time are added.
Bubble: if this is true, the event triggers the ancestor element of the bubble.
Cancelling: if this is true, the stopPropagation () method of the event object can be canceled.
Now, we need to schedule this event in a specific element, for example.
Document. getElementById ("msgbox"). dispatchEvent (event );
Any number of handlers can subscribe to this event using code such:
Document. addEventListener ("newMessage", newMessageHandler, false );
 
A standard event handler searches for the top HTML form submitted. This function obtains the current message. If it is valid, it sends a new "newMessage" event.
Var msgbox = document. getElementById ("msgbox ");
Msgbox. addEventListener ("submit", SendMessage, false );
// New message: Improves the newMessage event.
Function SendMessage (e ){
E. preventDefault ();
Var msg = document. getElementById ("msg"). value. trim ();
If (msg & window. CustomEvent ){
Var event = new CustomEvent ("newMessage ",{
Detail :{
Message: msg,
Time: new Date (),
},
Bubbles: true,
Cancelable: true
});
E. currentTarget. dispatchEvent (event );
}
}
The handler can now subscribe to "newMessage" events. This event only proposes that if there is a valid message, since the bubble is set to true, the event can be applied to a form or any of its ancestor such as the root document, for example.
// Listen to the newMessage event
Document. addEventListener ("newMessage", newMessageHandler, false );
// NewMessage event handler
Function newMessageHandler (e ){
LogEvent (
"Event subscriber on" + e. currentTarget. nodeName + ","
+ E. detail. time. toLocaleString () + ":" + e. detail. message
);
}
The message itself can extract details. The event object of the message attribute.
 
Browser compatibility
 
When writing this article, the objects are Chrome, Firefox, and Opera that support CustomEvent. It can be used in the night version of Safari so it is likely to arrive soon in the browser.
 
IE9 and earlier than unsupported objects. Fortunately, some JavaScript libraries support Custom Event delegation, so I continue to look at SitePoint for a cross-browser solution very quickly.

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.