Detailed description of writing custom events in JavaScript, detailed description of javascript

Source: Internet
Author: User

Detailed description of writing custom events in JavaScript, detailed description of javascript

We can customize events for more flexible development. When an event is used, it can be a powerful tool. Event-based development has many advantages (described later ).

Functions with custom events include Event, CustomEvent, and dispatchEvent.

Directly customize the Event and use the Event constructor:

var event = new Event('build');// Listen for the event.elem.addEventListener('build', function (e) { ... }, false);// Dispatch the event.elem.dispatchEvent(event);

CustomEvent allows you to create a custom event with a higher level and some data. The usage is as follows:

var myEvent = new CustomEvent(eventname, options);

Options can be:

{  detail: {    ...  },  bubbles: true,  cancelable: false}

Among them, detail can store some initialization information and can be called at the time of triggering. Other attributes are used to define whether the event has a bubble function.

Built-in events are triggered by the browser based on certain operations. Custom events need to be manually triggered. The dispatchEvent function is used to trigger an event:

element.dispatchEvent(customEvent);

The code above indicates that the customEvent event is triggered on the element. The combination is:

// add an appropriate event listenerobj.addEventListener("cat", function(e) { process(e.detail) });// create and dispatch the eventvar event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});obj.dispatchEvent(event);

You need to pay attention to compatibility when using custom events, but jQuery is much simpler:

// Bind Custom Event $ (element ). on ('mycustoment', function () {}); // trigger event $ (element ). trigger ('mycustoment'); in addition, you can pass more parameter information when triggering a Custom Event: $ ("p "). on ("myCustomEvent", function (event, myName) {$ (this ). text (myName + ", hi there! ") ;}); $ (" Button "). click (function () {$ ("p "). trigger ("myCustomEvent", ["John"]) ;});

JavaScript custom events are custom events that are different from standard events such as click and submit. Before describing the benefits of custom events, let's look at an example of a custom event:

<Div id = "testBox"> </div> // create the event var evt = document. createEvent ('event'); // defines the Event type evt. initEvent ('customent', true, true); // listens to the event var obj = document. getElementById ('testbox'); obj. addEventListener ('customent', function () {console. log ('memevent event triggered ');}, false );

For more information, see the Demo. Enter obj. dispatchEvent (evt) in the console. The "mevent event triggered" output in the console indicates that the custom event is successfully triggered.

In this process, the createEvent method creates an empty event evt, then uses the initEvent method to define the event type as a custom event, then listens to the corresponding elements, and then, the dispatchEvent is used to trigger the event.

Yes, the mechanism of custom events is the same as that of common events-listening to events, writing callback operations, and executing callback after triggering events. However, the difference is that custom events are completely triggered by our control, which means JavaScript decoupling. We can flexibly control multiple associated but complex operations using the mechanism of custom events.

Of course, you may have guessed that the above Code does not take effect in earlier IE versions. In fact, createEvent () is not supported in IE 8 or earlier versions (), there is a private fireEvent () method in IE, but unfortunately, fireEvent only supports standard event triggering. Therefore, we can use only one special and simple method to trigger custom events.

// Type is a custom event, for example, type = 'customobject'. callback is the callback function obj [type] = 0; obj [type] ++; obj. attachEvent ('onpropertychange', function (event) {if (event. propertyName = type) {callback. call (obj );}});

The principle of this method is to add a custom attribute to the DOM and listen to the propertychange event of the element. When the value of a DOM attribute changes, the callback of propertychange is triggered, in the callback, determine whether the changed property is our custom property. If so, execute the callback actually defined by the developer. This simulates the mechanism of custom events.

To enable the Custom Event mechanism to work with standard event listening and trigger simulation, a complete event mechanism is provided here. This mechanism supports listening to Standard Events and custom events, removes listeners and simulates trigger operations. It should be noted that, in order to make the code logic clearer, the custom Event is prefixed with 'custom' (for example, customTest, customAlert ).

/*** @ Description includes event listening, removal, and event trigger simulation. It supports chained calling **/(function (window, undefined) {var Ev = window. ev = window. $ = function (element) {return new Ev. fn. init (element) ;}; // Ev object build Ev. fn = Ev. prototype = {init: function (element) {this. element = (element & element. nodeType = 1 )? Element: document;},/*** add event listener ** @ param {String} type: Event type * @ param {Function} 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 + * // process custom events if (type. indexOf ('custom ')! =-1) {if (isNaN (_ that. element [type]) {_ that. element [type] = 0;} var fnEv = function (event) {event = event? Event: window. event if (event. propertyName = type) {callback. call (_ that. element) ;}}; _ that. element. attachEvent ('onpropertychang', fnEv); // store the bound propertychange callback on the element to facilitate the removal of event binding if (! _ That. element ['callback' + callback]) {_ that. element ['callback' + callback] = fnEv;} // standard event processing} else {_ that. element. attachEvent ('on' + type, callback) ;}} else {/*** @ supported For Others */_ that. element ['on' + type] = callback;} return _ that ;}, /*** remove event listener ** @ param {String} type the event type monitored * @ param {Function} callback function */remove: Function (type, callback) {var _ that = this; if (_ that. e Lement. removeEventListener) {/*** @ supported For Modern Browers and IE9 + */_ that. element. removeEventListener (type, callback, false);} else if (_ that. element. detachEvent) {/*** @ supported For IE5 + * // process custom events if (type. indexOf ('custom ')! =-1) {// remove the listener _ that for the corresponding custom attribute. element. detachEvent ('onpropertychang', _ that. element ['callback' + callback]); // Delete the callback _ that for the Custom Event stored in the DOM. element ['callback' + callback] = null; // processing of Standard Events} else {_ that. element. detachEvent ('on' + type, callback) ;}} else {/*** @ supported For Others */_ that. element ['on' + type] = null;} return _ that ;}, /*** trigger event simulation ** @ param {String} type: Event type of the trigger event simulation * @ retu Rn {Object} returns the current Kjs Object */trigger: function (type) {var _ that = this; try {// modern browser if (_ that. element. dispatchEvent) {// create event var evt = document. createEvent ('event'); // defines the Event type evt. initEvent (type, true, true); // trigger event _ 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) // introduce the event mechanism //... // capture DOMvar testBox = document. getElementById ('testbox'); // callback function 1 function triggerEvent () {console. log ('triggering a Custom Event mmconsole');} // callback function 2 function triggerAgain () {console. log ('the custom event customconsole' is triggered again);} // encapsulate testBox =$ (testBox); // bind two callback functions at the same time and support the chained call of testBox. add ('customconsole', triggerEvent ). add ('customconsole', triggerAgain );

Complete code is available in Demo.

Open the Demo and call testBox in the console. trigger ('customconsole') triggers a custom event. You can see that the console outputs two prompts and then input testBox. remove ('customconsole', triggerAgain) removes the last listener and then uses testBox. trigger ('customconsole') triggers a custom event. You can see that the console outputs only one prompt, that is, the last listener is successfully removed. Now all functions of the event mechanism work properly.

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.