7.1 Event Bubbling (이벤트 버블링)
JavaScript에서는 한 요소에서 발생한 이벤트가 DOM 트리를 통해 퍼질 수 있어. 이 과정을 이벤트 전파라고 하며, 두 가지 주요 메커니즘이 있어: 이벤트 버블링 (event bubbling)과 이벤트 캡처링 (event capturing).
이벤트 전파 메커니즘:
- Event Bubbling (이벤트 버블링).
- Event Capturing (이벤트 캡처링).
이벤트 버블링은 자식 요소에서 발생한 이벤트가 부모 요소를 거쳐 최상위 요소(document
일 때가 많아)로 차례로 퍼져나가는 과정이야.
설명:
- 버튼
child
가 클릭되면, 먼저child
요소에서 이벤트 핸들러가 작동해 (Child clicked
). - 그 후 이벤트는
parent
요소로 버블링되고, 그 핸들러가 작동해 (Parent clicked
).
예시:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
});
child.addEventListener('click', function(event) {
console.log('Child clicked');
});
</script>
</body>
</html>
7.2 Event Capturing (이벤트 캡처링)
이벤트 캡처링은 이벤트가 최상위 요소로부터 발생한 목표 요소까지 부모 요소를 거쳐 내려가는 과정이야.
이벤트 캡처링을 사용하려면, 이벤트 핸들러를 추가할 때 capture
파라미터를 true
로 설정해야 해.
설명:
- 버튼
child
가 클릭되면, 먼저capture
파라미터가true
로 설정되어 있어parent
요소의 이벤트 핸들러가 작동해 (Parent clicked
). - 그 후 이벤트는 목표 요소인
child
에 도달하여, 그 핸들러가 작동해 (Child clicked
).
예시:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Event Capturing Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
}, true);
child.addEventListener('click', function(event) {
console.log('Child clicked');
});
</script>
</body>
</html>
7.3 이벤트 전파의 세 가지 단계 모델
DOM에서 이벤트 처리는 세 가지 단계로 이루어져:
1. Capturing Phase (캡처링 단계). 이벤트는 최상위 요소(보통 document)로부터 목표 요소로 부모 요소를 거쳐 내려가.
2. Target Phase (목표 단계). 이벤트는 이벤트가 발생한 목표 요소에 도달해.
3. Bubbling Phase (버블링 단계). 이벤트는 목표 요소로부터 부모 요소를 거쳐 최상위 요소로 퍼져나가.
이벤트 전파 제어
이벤트 전파를 제어하기 위한 메소드가 있어:
stopPropagation()
. 이벤트 전파를 버블링 중이든 캡처링 중이든 중단해.stopImmediatePropagation()
. 현재 요소에서 다른 이벤트 핸들러를 실행하는 것을 방지하고 이벤트 전파를 중지해.preventDefault()
. 이벤트와 관련된 기본 동작(예: 버튼 클릭 시 폼 제출)을 취소해.
7.4 stopPropagation 사용 예시
설명:
- 버튼
child
가 클릭되면,child
요소의 이벤트 핸들러가 작동해 (Child clicked
). - 이벤트 전파는
event.stopPropagation()
을 사용하여 중단되며,parent
요소의 이벤트 핸들러는 작동하지 않아.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Stop Propagation Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
});
child.addEventListener('click', function(event) {
console.log('Child clicked');
event.stopPropagation(); // 이벤트 버블링을 중단해
});
</script>
</body>
</html>
GO TO FULL VERSION