Js event listening encapsulation (supports anonymous functions)

Source: Internet
Author: User

There are a lot of scenarios for event listening in js. It is nothing more than determining whether the browser supports addEventListener and attachEvent. There are many methods to search for event listening on the Internet, but there are still some incomplete methods. In the following method, the method for adding event listening is the same, but a point operation is performed on the unbinding event. Now anonymous functions can be used, therefore, when binding events, you no longer need to name functions separately.

Main Code:

The Code is as follows: Copy code

/* Bind events and unbind events */
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 is used to cache events in the hash table. handleHash ['event name'] is an array to add multiple event listening methods, when unbind events, traverse the array of handleHash ['event name'] And then remove it.

Usage:

The Code is as follows: Copy code

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

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.