Explain the basics of custom event writing in JavaScript

Source: Internet
Author: User
Tags event listener

We can customize events to achieve more flexible development, and events can be a powerful tool, and event-based development has many advantages (described later).

Functions with custom events are event, Customevent, and dispatchevent.

To customize the event directly, 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 can create a more highly customized event and can also include some data, as follows:

var myevent = new Customevent (eventname, Options);

The options can be:

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

Where detail can hold some initialization information that can be invoked at the time of triggering. Other properties are the ability to define whether the event has bubbles, and so on.

Built-in events are triggered by the browser based on certain actions, and 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 event triggers customevent on the element. Combined with this is:

Add an appropriate event listener
Obj.addeventlistener ("Cat", Function (e) {process (E.detail)});

Create and dispatch the event
var event = new Customevent ("cat", {"detail": {"Hazcheeseburger": True}});
Obj.dispatchevent (event);

Using custom events requires attention to compatibility issues, and using JQuery is much simpler:

Bind custom Event
$ (Element). On (' Mycustomevent ', function () {});

Trigger event
$ (Element). Trigger (' mycustomevent ');
In addition, you can also 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 customized events that differ from standard events such as click, submit, and before describing the benefits of custom events, look at an example of a custom event:

<div id= "Testbox" ></div>

//Create event
var evt = document.createevent (' event ');
Defines the event type
evt.initevent (' customevent ', true, true);
Listening for events on elements
var obj = document.getElementById (' Testbox ');
Obj.addeventlistener (' Customevent ', function () {
  console.log (' customevent event triggered ');
}, false;

The effect can view the Demo, enter obj.dispatchevent in the console (EVT), you can see the output "Customevent event triggered" in the console, indicating that the custom event was triggered successfully.

In this process, the CreateEvent method creates an empty event evt, and then uses the Initevent method to define the type of the event as a predefined custom event, 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 normal events-listening events, write callback operations, triggering events, and then executing callbacks. But the difference is that the custom event is completely controlled by us to trigger the timing, which means implementing a JavaScript decoupling. We can flexibly control multiple, but logically complex, operations using the mechanism of custom events.

Of course, as you may have guessed, the above code does not work in the lower version of IE, in fact, in IE8 and the following version of IE does not support createevent (), but 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 the callback function that is actually defined for the developer
Obj[type] = 0;
obj[type]++;
 
Obj.attachevent (' Onpropertychange ', function (event) {
  if (event.propertyname = = type) {
    callback.call (obj);
  }
});

The principle of this method is actually to add a custom attribute to the DOM while listening for the PropertyChange event of the element, which triggers a PropertyChange callback when the value of a property of the DOM changes. Again, in the callback, determine if the changed attribute is our custom attribute, or execute the callback that the developer actually defined. This simulates the mechanism of custom events.

To enable the mechanism of custom events to match the monitoring and simulation triggers of standard events, here is a complete event mechanism that supports the monitoring of standard and custom events, and the removal of listening and simulating triggering operations. It should be noted that, in order to make the logic of the code clearer, a custom event is defined here with the prefix of ' custom ' (for example: Customtest,customalert).

/** * @description The event mechanism that contains event sniffing, removal, and impersonation event triggering, support for chained calls */(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.nodety PE = = 1)?
  Element:document; /** * Add Event Listener * * @param {String} type listens for event type * @param {function} callback callback function * * Add:functio
     
    N (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;
 
  var Fnev = function (event) {        event = event?
          Event:window.event if (event.propertyname = = type) {Callback.call (_that.element);
 
        }
        };
 
        _that.element.attachevent (' Onpropertychange ', Fnev); Stores a bound PropertyChange callback on an element to facilitate the removal of event bindings if (!_that.element[' callback ' + callback]) {_that.elemen
 
        T[' 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 listens for event type * @param {function} callback callback function * * REMOVE:FU
     
    Nction (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) {//Remove the listener for the corresponding custom attribute _that.element.detachevent (' Onpropertychange ',
 
        _that.element[' callback ' + callback]);
      
      Deletes the callback for custom events 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] = nul
       
    L
 
  return _that; /** * Simulates triggering event * @param {String} type simulates the event type that triggers the event * @return {object} returns the current KJS object * * Trigger:fun
     
    Ction (type) {var _that = this; try {//modern browser if (_that.element.dispatchevent) {//create event var evt = document.createevent (' Even T ');
        Defines the type of the event evt.initevent (type, true, true);
      Trigger Event _that.element.dispatchevent (EVT); IE} else if (_that.element.fireevent) {if (Type.indexof (' Custom ')!=-1) {_that.el
 
        ement[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 event mechanism//...//capture DOM var testbox = document.getElementById (' Testbox '); callback function 1 function triggerevent () {console.log (' triggers a custom event customconsole ');}//Callback functions 2 function Triggeragain () {con
Sole.log (' Once again triggers a custom event customconsole ');
}//Package Testbox = $ (testbox);

 Bind two callback functions at the same time, support chained call Testbox.add (' Customconsole ', triggerevent). Add (' Customconsole ', triggeragain);

Complete code 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 to remove the latter listener, then use Testbox.trigger (' Customconsole ') to trigger the custom event, you can see the console output only one prompt, That is, the last listener is successfully removed, and all functions of this event mechanism work correctly.

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.