Learning notes for JavaScript custom events

Source: Internet
Author: User
Tags event listener

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:

The code is as follows Copy Code


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

Creating events
var evt = document.createevent (' Event ');
Defining event Types
Evt.initevent (' Customevent ', true, true);
Listening for events on elements
var obj = document.getElementById (' Testbox ');
Obj.addeventlistener (' Customevent ', function () {
Console.log (' customevent event triggers ');
}, 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.

The code is as follows Copy Code
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).

The code is as follows Copy Code

/**
* @description The event mechanism that contains event sniffing, removal, and impersonation event triggering, supporting chained calls
* @author Kayo Lee (kayosite.com)
* @create 2014-07-24
*
*/

(Function (window, undefined) {

var Ev = window. Ev = window.$ = function (Element) {

return new Ev.fn.init (element);
};

Ev Object Building

Ev.fn = Ev.prototype = {

Init:function (Element) {

This.element = (element && element.nodetype = 1)? Element:document;
},

/**
* Add Event Listener
*
* @param the type of event monitored by {String} 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;

}

var Fnev = function (event) {

event = event? Event:window.event

if (Event.propertyname = = type) {
Callback.call (_that.element);
}
};

_that.element.attachevent (' Onpropertychange ', Fnev);

Storing bound PropertyChange callbacks on elements for easy 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 the type of event monitored by {String} 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 attribute
_that.element.detachevent (' Onpropertychange ', _that.element[' callback ' + callback]);

Delete a 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] = NULL;

}

return _that;

},

/**
* Simulate Trigger Event
* @param {String} type simulates the event type that triggers the event
* @return {Object} returns the current KJs object
*/

Trigger:function (type) {

var _that = this;

try {
Modern browsers
if (_that.element.dispatchevent) {
Creating events
var evt = document.createevent (' Event ');
Define the type of event
Evt.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)

  code is as follows copy code
//test Case 1 (custom event test)
//Introduce event mechanism
//...
//Capture DOM
var testbox = document.getElementById (' Testbox ');
//callback function 1
function triggerevent () {
 & nbsp;      Console.log (' Triggers a custom event customconsole ');
}
//callback function 2
function Triggeragain () {
        console.log (' Once again triggers the custom event customconsole ');
}
//package
Testbox = $ (testbox);
//Bind two callback functions, support chained calls
Testbox.add (' Customconsole ', triggerevent). Add (' Customconsole ', triggeragain);

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) removes the latter listener, then uses Testbox.trigger (' Customconsole ') to trigger the custom event, and you can see that the console outputs only one prompt, that is, successfully removing the latter listener. All features of this event mechanism work correctly.

Test Case 2 (standard event test)

The code is as follows Copy Code
Test Case 2 (standard event test)
Introducing Event mechanisms
// ...
Capturing DOM
var Testclick = document.getElementById (' Testclick ');
callback function
function Triggerevent () {
Alert (' Wipe, I was ruthlessly clicked! ');
}
Packaging
Testclick = $ (testbox);
Listening
Testclick.add (' click ', triggerevent);

Also this Demo, call Testclick.trigger (' click ') in the console to trigger click to observe the effect

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.