wuxianqiang / blog

博客系列
17 stars 4 forks source link

delegate实现事件委托 #274

Open wuxianqiang opened 4 years ago

wuxianqiang commented 4 years ago
  <ul id="wrapper">
    <li class="item">1</li>
    <li class="item">1</li>
    <li class="item">1</li>
  </ul>
  <script>
    let _events = []
    function delegate(parentElement) {
      function on(selector, eventType, fn) {
        function handler(e) {
          let el = e.target
          while (!el.matches(selector)) {
            if (parentElement === el) {
              el = null
              break
            }
            el = el.parentNode
          }
          el && fn.call(el, e, el)
        }
        parentElement.addEventListener(eventType, handler)
        _events.push({ handler, selector, eventType, fn })
        return parentElement
      }
      function off(selector, eventType, fn) {
        let index = _events.findIndex(item => {
          return item.fn === fn && item.eventType === eventType && item.selector === selector
        })
        if (index > -1) {
          let target = _events[index]
          parentElement.removeEventListener(eventType, target.handler)
          _events.splice(index, 1)
        }
      }
      return { on, off }
    }

    let parent = document.getElementById('wrapper')
    function callback() {
      console.log('ok')
    }
    delegate(parent).on('.item', 'click', callback);
    delegate(parent).off('.item', 'click', callback);

  </script>
</body>