JavaScript Custom Events

Source: Internet
Author: User
Tags event listener

JavaScript custom events are custom events that differ from standard events such as click, submit, and before you describe the benefits of a custom event, consider an example of a customized event:

Html

<id= "Testbox"></div>

Javascript:

// Create Event var evt = document.createevent (' Event '); // Defining event Types true true ); // listening for events on an element var obj = document.getElementById (' Testbox '); Obj.addeventlistener (function( {    Console.log (' customevent event triggered 'false);

Specific effects can be viewed in the Demo, input obj.dispatchevent (EVT) in the console, you can see the output "Customevent event triggered" in the console, indicating that the custom event triggered successfully.

In this process, the CreateEvent method creates an empty event evt, and then uses the Initevent method to define the type of event as a custom event that is well-defined, then listens to the corresponding element, and then uses the dispatchevent to trigger the event.

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.

Of course, you may have guessed that the above code in the lower version of IE does not take effect, in fact, in IE8 and the following version of IE does not support createevent (), and the IE Private fireEvent () method, but unfortunately, fireEvent only support the trigger of standard events 。 Therefore, we can only use a special and simple method to trigger a custom event.

// type is a custom event, such as type = ' Customevent ', callback is the developer's actual defined callback function Obj[type] = 0; Obj[type]+ +; Obj.attachevent (function(event) {    if(event.propertyname = = type) {        Callback.call (obj);    }});

To enable the mechanism of custom events to match the listening and simulation triggers of standard events, a complete event mechanism is presented, which supports monitoring of standard events and custom events, and the removal of listening and triggering actions. It is important to note that in order to make the logic of the code clearer, it is agreed that the custom event is prefixed with ' custom ' (for example: Customtest,customalert). the principle of this method is actually to add a custom attribute to the DOM, while listening to the element's PropertyChange event, which triggers the PropertyChange callback when the value of one of the DOM's properties changes. Then in the callback to determine whether the changed property is our custom property, if the developer actually defines the callback. This simulates the mechanism of custom events.

/** * @description includes event monitoring, removal, and event triggering event mechanism to support chained calls * @author Kayo Lee (kayosite.com) * @create 2014-07-24 **/ (function(window, undefined) {varEv = window. Ev = window.$ =function(Element) {return NewEv.fn.init (element);}; //Ev Object ConstructionEv.fn= Ev.prototype ={init:function(Element) { This. Element = (element && Element.nodetype = = 1)?element:document; },     /** * Add Event Listener * * @param {String} type listen for event type * @param {function} callback callback function*/Add:function(Type, callback) {var_that = This; if(_that.element.addeventlistener) {/** * @supported for modern browers and ie9+*/_that.element.addeventlistener (Type, callback,false); } Else if(_that.element.attachevent) {/** * @supported for ie5+*/             //Custom Event Handling            if(Type.indexof (' custom ')! =-1 ){                 if(IsNaN (_that.element[type])) {_that.element[type]= 0; }                  varFnev =function(Event) {event= event?event:window.eventif(Event.propertyname = =type)                    {Callback.call (_that.element);                 }                }; _that.element.attachevent (' Onpropertychange ', Fnev); //stores the callback of the bound PropertyChange on the element to facilitate the removal of event bindings                if(!_that.element[' callback ' +Callback]) {_that.element[' Callback ' + callback] =Fnev; }                   //Standard event Handling}Else{_that.element.attachevent (' On ' +type, callback); }                     } Else {                         /** * @supported for Others*/_that.element[' on ' + type] =callback; }         return_that; },     /** * Remove Event Listener * * @param {String} type Listener Event type * @param {function} callback callback function*/Remove:function(Type, callback) {var_that = This; if(_that.element.removeeventlistener) {/** * @supported for modern browers and ie9+*/_that.element.removeeventlistener (Type, callback,false); } Else if(_that.element.detachevent) {/** * @supported for ie5+*/                         //Custom Event Handling            if(Type.indexof (' custom ')! =-1 ){                 //to remove the listener for the corresponding custom property_that.element.detachevent (' Onpropertychange ', _that.element[' callback ' +callback]); //To delete a callback for a custom event stored on the DOM_that.element[' callback ' + callback] =NULL; //handling of standard events}Else{_that.element.detachevent (' On ' +type, callback); }         } Else {                         /** * @supported for Others*/_that.element[' on ' + type] =NULL; }         return_that; },         /** * Simulated trigger event * @param {String} type to simulate event type triggering event * @return {object} returns the current KJs object*/Trigger:function(type) {var_that = This; Try {                //Modern Browsers            if(_that.element.dispatchevent) {//Create Event                varEVT = document.createevent (' Event '); //define the type of eventEvt.initevent (Type,true,true); //Triggering Events_that.element.dispatchevent (EVT); //IE}Else if(_that.element.fireevent) {if(Type.indexof (' custom ')! =-1) {_that.element[type]++; } Else{_that.element.fireevent (' On ' +type); }                   }         } Catch(e) {}; return_that; }} Ev.fn.init.prototype=Ev.fn;}) (window);

Test Case 1 (custom event test)

//test Case 1 (custom event test)//Introducing Event Mechanisms// ...//capturing the DOMvarTestbox = document.getElementById (' Testbox '));//callback function 1functiontriggerevent () {Console.log (' Triggered a custom event Customconsole ');}//callback function 2functionTriggeragain () {Console.log (' Once again triggered a custom event Customconsole ');}//PackageTestbox =$ (testbox);//bind two callback functions simultaneously, support chained callTestbox.add (' Customconsole ', triggerevent). Add (' Customconsole ', triggeragain);

The complete code is in Demo.

After opening the Demo, call Testbox.trigger (' Customconsole ') in the console to trigger the custom event itself, you can see the console output two prompts, and then enter Testbox.remove (' Customconsole ', Triggeragain) remove the latter listener, then use Testbox.trigger (' Customconsole ') to trigger the custom event, you can see the console only output a prompt, That is, after successfully removing the last listener, all the functions of this event mechanism are working properly.

Test Case 2 (standard event test)

// test Case 2 (standard event test) // Introducing Event Mechanisms //  ... // capturing the DOM var testclick = document.getElementById (' Testclick '); // callback function function triggerevent () {    alert (' wipe, I've been ruthlessly clicked! ');} // package Testclick = $ (testbox); // Monitor testclick.add (' click ', triggerevent);


The copyright is also the Demo, which can be observed by invoking Testclick.trigger (' click ') in the console to trigger the click.

This article was published by Kayo Lee , this article link:http://kayosite.com/javascript-custom-event.html

JavaScript Custom Events

Related Article

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.