javaScript event handling is the foundation of all client applications. When an event occurs on the target element, such as button click, mouse movement, form submission, etc., a handler function is executed. An event object passed to the handler provides various properties and a number of methods to prevent violations.
One drawback is that events are inevitably associated with DOM elements. Consider a simple form that accepts a message from the user:
We can write a handler to echo the message when the screen is submitted, such as .
document.getElementById("msgbox").addEventListener("submit", function(e) {
e.preventDefault();
var msg = e.currentTarget.getElementById("msg").value.trim();
if (msg) {
alert(msg);
}
}, false);
What if we also want to send the message as a tweet, store it on a server, or perform other actions? We have two options with the current There are event delegate methods:
1, adding code to our existing further handler.
This is where we need to update since we have rigidified and tested our handler functions every time we add, change or remove functionality. There may be dozens of uses for the published message, and we are trying to apply them all in the same block of code.
2 event handlers are created further for each use.
This will lead to more elegant code which leads to maintenance issues. First, each function must perform similar actions to extract and validate the message. What if we need to change our form? Simply renaming the ID requires us to change the event handling code for each subscriber.
Wouldn’t it be nice if we could simply raise a custom “newMessage” event whenever a valid message is posted? It would even be better if we could simply monitor the document or body tag instead of referencing a specific form node. This is exactly what custom events allow us to do.
Raising a custom event is easy; we pass the name, details and select a new CustomEvent object:
var event = new CustomEvent(
"newMessage",
{
detail: {
message: "Hello World!",
time: new Date(),
},
bubbles: true,
cancelable: true
}
);
In this example, "newMessage" is a customized event type. The second parameter is an object with three properties:
Details: A child object providing customized event information. In this example, we added a message and time.
Bubble: If this is true, the event will be bubbled on the ancestor element that triggered the event.
Cancelable: If this is true, the event can be canceled using the event object's stopPropagation() method.
Now, we need to dispatch this event on a specific element, eg.
document.getElementById("msgbox").dispatchEvent(event);
Any number of handlers can subscribe to this event using code such as:
document.addEventListener("newMessage", newMessageHandler, false);
A standard event handler The program looks for the submitted HTML form above. This function gets the current message, assumes it is valid, and dispatches a new "newMessage" event.
var msgbox = document.getElementById("msgbox");
msgbox.addEventListener("submit", SendMessage, false);
// New message: raise 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);
}}
Treatment program can now subscribe to the "NewMessage" event. This event is only raised if there is a valid message, and since bubble is set to true, the event can be applied to the form or any of its ancestors 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 details can be extracted from the message itself. Event object for message properties.
Browser Compatibility
At the time of writing, the target is Chrome, Firefox and Opera that support CustomEvent. It's available in nightly versions of Safari so it's likely to arrive soon, for the browser.
IE9 and below do not support objects. Luckily, some JavaScript libraries support custom event delegation, so keep looking at SitePoint for a cross-browser solution soon.