Class: 제로베이스
Created: December 28, 2022 7:26 AM
Type: Javascript
강의 명: 초심자도 빈틈없이 학습하는 자바스크립트
bubbling은 특정 요소에서 event가 발생했을 때 상위 요소로 event가 전파되는 것
- 브라우저에서 event bubbling이 발생하면
- 최상위 요소인 document 객체에 도달할 때까지 상위로 이벤트가 전파된다.
- 이벤트가 전파되는 것을 확인하려면 위와 같이 태그에 handler가 필요하다.
- focus와 같이 bubbling이 발생하지 않는 이벤트들을 제외하고 대부분의 이벤트들은 bubbling이 발생
capturing은 특정 요소에서 event가 발생했을 때 bubbling과 반대로 하위 요소로 event가 전파되는 것을 의미한다.
- 브라우저에서 event capturing이 발생하면
- 최상위 요소인 document 객체로부터 이벤트가 발생한 target 요소에 도달할 때까지 하위로 이벤트가 전파된다.
- capturing을 확인하기 위해서는 addEventListener()의 capture 옵션을 true로 설정해주면 된다.
브라우저에서 event가 발생했을 때 실제로 이벤트가 발생한 요소를 target 요소라고 한다. event.target을 이용하여 접근할 수 있다.
<form id="form">form
<div>div
<p>p</p>
</div>
</form>
<script>
const target = document.getElementById('form')
target.onclick = function(event) {
console.log('event.target.tagName', event.target.tagName);
console.log('this', this.tagName);
};
</script>
event.target과 같이 확인한 this는 event.currentTarget과 동일하며 다음과 같은 차이점이 있다
이벤트 발생 시 다른곳으로 전파를 중단시킴
<div class="parent">
<button id="btn">button</button>
</div>
<script>
const elements = document.querySelectorAll('*');
elements.forEach((item) => {
item.addEventListener( 'click' , (event) => {
event.stopPropagation();
console.log('bubbling: ' + item.tagName);
}, {
capture: false
}
);
});
</script>
이벤트의 기본 동작을 중단
// HTML
<a href="https://cheonmro.github.io/">블로그로 이동</a>
// Javascript
var elem = document.querySelector('a');
elem.addEventListener('click', function (e) {
console.log(e.cancelable); // true
// 이벤트의 기본 동작을 중단
e.preventDefault();
});
이벤트의 전파(버블링 / 캡처링)를 중단
어느 한 요소를 이용하여 이벤트를 처리한 후, 이벤트가 부모 요소로 이벤트가 전파되는 것을 중단하기 위해 사용되는 메소드이다.
// HTML
<div id="divBox">
<p id="paraBox">블로그
<a id="linkBox" href="https://cheonmro.github.io/">클릭</a>
</p>
</div>
// Javascript
document.getElementById("divBox").addEventListener("click", clickDiv);
document.getElementById("paraBox").addEventListener("click", clickPara);
document.getElementById("linkBox").addEventListener("click", clickLink);
function clickDiv(event) {
console.log('Event for div');
}
function clickPara(event) {
console.log('Event for p');
}
function clickLink(event) {
event.stopPropagation(); // 이벤트의 전파를 중단함.
console.log('Stop Propagation!')
}
이벤트를 제어하는 이유? 과도한 이벤트 발생시 성능이 저하될 수 있기 때문.
두 개념 모두 비슷한 용도로 사용되는데, 이벤트나 함수의 실행 빈도를 조절하여 성능상의 이점을 누리기 위한 목적으로 사용한다.
위의 설명에서 알 수 있는 점은 두 방식 모두 이벤트 발생 빈도를 조절할 수 있다는 점이다. 본인이 무엇에 중점을 두고 구현을 하느냐에 따라 둘 중 어떤 방식을 사용할 것인가를 결정할 수 있다.
<input type="text" onkeyup="debounce()">
<script>
let timer;
function debounce(event) {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
console.log('debounce :: ' + timer)
}, 200)
}
</script>
<input type="text" onkeyup="throttle()">
<script>
let timer;
function throttle(event) {
if(!timer) {
timer = setTimeout(() => {
console.log('throttle :: ' + timer)
}, 3000)
}
}
</script>