代理绑定的情况下,点击一次“激活”,触发了两次回调。普通绑定不会出现这种情况。
<ul id="box">
<li id="active">激活</li>
<li>取消</li>
<li>取消</li>
</ul>
function myBindEvent(element, type, selector, cb) {
if (typeof selector === 'function') {
cb = selector;
selector = null;
}
element.addEventListener(type, event => {
const target = event.target;
console.log('selector:', selector)
if (selector) {
// 代理
if (target.matches(selector)) {
console.log(1)
cb.call(target, event)
}
} else {
// 普通
console.log(2)
cb.call(target, event)
}
}, true)
}
const box = document.getElementById('box');
myBindEvent(box, 'click', '#active', function (e) {
e.stopPropagation()
e.preventDefault()
console.log(this.innerHTML)
})
myBindEvent(box, 'click', function (e) {
console.log(this.innerHTML)
})