Yes, the mechanism for customizing events is the same as for normal events-listening for events, writing callback operations, and executing callbacks after triggering an event. But the difference is that the custom event is completely controlled by our trigger timing, which means a JavaScript decoupling is implemented. We can flexibly control multiple, but logically complex, operations using the mechanism of custom events.
The code demonstrates the following:
1<! DOCTYPE html>2345<body>6 7<div id= "Div2" > Hello. This is a DIV element. </div>8 9<script>Ten varevent = document.createevent ("event");//Create Event OneEvent.initevent ("My",true,true);//Initializing Events A varDom = document.getElementById ("Div2"); -Dom.addeventlistener ("My",function() {alert ("OK")},false);//Monitoring Events -Dom.dispatchevent (event);//Triggering Events the</script> -</body> -Related function Comments:
1. Create Event document.createevent (type);
Type is a string, that represents the type of event to being created. Possible event types include "Uievents", "mouseevents", "mutationevents", and "htmlevents". See Notes sections for details.
2. Initializing events
Event.initevent (eventtype,canbubble,cancelable)
Parameter description:
EventType the string value. The type of the event. The name of the new event.
Whether the Canbubble event is bubbling.
Cancelable whether the event can be canceled with the Preventdefault () method.
3. Listen for event events
Target.addeventlistener (' dataavailable ', Handler, false);
Parameter description:
Dataavailable New event Name
Handler triggered functions
False if the event model is being obtained
4. Triggering events
Target.dispatchevent (e);
E is an already declared event object
JavaScript Custom Events