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
}
});