Open nicoleJT914 opened 7 years ago
使用handleHash缓存事件的回调
<body> <button id="btn">click</button> <script> var handleHash = {} var bind = (function() { if (window.addEventListener) { return function(el, type, fn, capture) { var capture = capture || false el.addEventListener(type, function() { fn() handleHash[type] = handleHash[type] || [] handleHash[type].push(arguments.callee) }, capture) } } else if (window.attchEvent) { return function(el, type, fn) { el.attchEvent('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]) { handleHash[type].forEach(function(item) { el.removeEventListener(type, item) }) } } } else if (window.attachEvent) { return function(el, type) { if (handleHash[type]) { handleHash[type].forEach(function(item) { el.detachEvent('on'+type, item) }) } } } })() // 调用 var btn = document.getElementById('btn') bind(btn, 'click', function abb () { alert('ok') }, false) setTimeout(function() { console.log('start') unbind(btn, 'click') }, 2000) </script> </body>
使用handleHash缓存事件的回调