nicoleJT914 / blog

一只游行的火烈鸟/用issues记博客
0 stars 0 forks source link

封装事件监听函数(支持匿名函数) #36

Open nicoleJT914 opened 7 years ago

nicoleJT914 commented 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>