Encapsulates a JavaScript event listener _javascript trick that supports anonymous functions

Source: Internet
Author: User
Tags event listener

About JS in the event monitoring everyone uses more, but is to determine whether the browser support AddEventListener and attachevent, online search on the event monitoring methods are quite many, but some are not very perfect. The following method is the same for adding event sniffing, except that a little surgery is done on the cancellation of the event bindings and now supports the use of anonymous functions, so you no longer need to name the function separately when binding the event.


Main code:

Copy Code code as follows:

/* Bind event and Unbind * *
var handlehash = {};
var bind = (function () {
if (Window.addeventlistener) {
return function (EL, type, FN, capture) {
El.addeventlistener (type, function () {
FN ();
Handlehash[type] = Handlehash[type] | | [];
Handlehash[type].push (Arguments.callee);
}, capture);
};
else if (window.attachevent) {
return function (EL, type, FN, capture) {
El.attachevent ("On" + Type, function () {
FN ();
Handlehash[type] = Handlehash[type] | | [];
Handlehash[type].push (Arguments.callee);
});
};
}
})();
var unbind = (function () {
if (Window.addeventlistener) {
return function (el, type) {
if (Handlehash[type]) {
var i = 0, len = handlehash[type].length;
for (i; i<len; i + 1) {
El.removeeventlistener (type, handlehash[type][i]);
}
};
};
else if (window.attachevent) {
return function (el, type) {
if (Handlehash[type]) {
var i = 0, len = handlehash[type].length;
for (i; i<len; i + 1) {
El.detachevent ("On" + Type, handlehash[type][i]);
}
};
};
}
})();

Principle Analysis:

Handlehash do hash Table cache event function,handlehash[' event name ' is an array to add multiple event listener methods, unbind which event to traverse handlehash[' event name ' of the array, and then remove.

Use:

Copy Code code as follows:

Bind (obj, ' click ', function () {
Alert (' click ');
});
Unbind (obj, ' click ');

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.