bindEvent - 通用事件绑定

175 阅读1分钟

概念描述

  • 通用事件绑定
  • 事件委托 && 非事件委托
  • 执行回调,需要绑定 this(this 指向事件操作者 e.target 而不是 e.currentTarget) 和参数

代码实现

/**
* @description: bindEvent
* @author: huen2015
*/

function bindEvent(type: string, el: Element, fn: Function, selector?: string) {
    el.addEventListener(type, function (this: any, e: Event) {
        if (selector) {
            const target = e.target
            if (target) {
                if ((target as Element).matches(selector)) {
                    fn.call(target, e)
                }
            }
        } else {
            fn.call(this, e)
        }
    })
}

const bindEventDom = document.querySelector('#bindEvent')
const bindEventButtonDom = document.querySelector('#bindEventButton')
if (bindEventDom) {
    // 事件委托
    bindEvent('click', bindEventDom, function (this: any, e: PointerEvent) {
        console.log('this', this)
        console.log('e', e)
    }, 'a')
}
if (bindEventButtonDom) {
    // 非事件委托
    bindEvent('click', bindEventButtonDom, function (this: any, e: PointerEvent) {
        console.log('this', this)
        console.log('e', e)
    })
}

代码演示仓库