概念描述
- 通用事件绑定
- 事件委托 && 非事件委托
- 执行回调,需要绑定 this(this 指向事件操作者 e.target 而不是 e.currentTarget) 和参数
代码实现
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)
})
}