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 '); |