Event 事件

Node.js Event 事件

事件传递

什麽是 Event Bubbling (propagation), Event Capturing

前端工程师需要处理画面,所以会有事件在不同阶层 DOM 传递的状况

Event Bubbling

从启动事件的元素节点开始,逐层往上传递

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Event Capturing

从最上层的母元素开始,逐层往下传递

the event goes down to the element.

事件两者都会执行 ,会先执行 Capturing 再执行 Bubbling

抓取事件

var btn = document.getElementById('btn');

// Event Bubbling
btn.addEventListener('click', function(){
  console.log('HELLO');
}, false );

// Event Capturing
btn.addEventListener('click', function(){
  console.log('HELLO');
}, true );

取消 Event Bubbling

event.stopPropagation();

什麽是 Event Delegation?

Event Delegation是一种运用 Event Bubbling 概念而能减少监听器数目的方法,将事件处理器绑在目标元素的父元素上进行处理,可以减少大量子事件监听器的数量

If there are many elements inside one parent, and you want to handle events on them — don’t bind handlers to each element. Instead, bind the single handler to their parent and get the child from e.target

<ul id="list">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
    <li><a href="#">4</a></li>
    <li><a href="#">5</a></li>
</ul>

若选单中要在 li 选项绑定事件,那选项越多绑定的事件就越多,消耗的记忆体就越大,那麽会决定将事件绑定在 ul.list 上,然后靠着 Event Bubbling 的特性在上层抓到点击 li 事件,去处理事件函数,那这样只需要绑定一个事件就好

// 绑定在 li 所有连结元素
// Before using delegated event
let elements = document.querySelectorAll('ul > li > a');
for (let elem of elements) {
    elem.addEventListener('click', function(e){
       console.log(e.target)
      // to something
    })
}

// 绑定在 ul.list 连结元素母节点
// Attach a delegated event handler
document.getElementById('list').addEventListener('click', function(e){
    if (e.target.tagName == 'a'){
      console.log(e.target)
      // to something
    }
});

参考资料