기록

이벤트 버블링과 캡처링

해은 2020. 9. 9. 00:56

이벤트 버블링과 캡처링에 대해 얘기하기에 앞서 HTML 구조에 대해 간단히 설명하자면 HTML는 아래와 같은 트리 구조를 갖는다.

 

 

 

 

 


이벤트 버블링이란?

한 엘리먼트에서 이벤트가 발생했을 때 해당 이벤트가 엘리먼트의 계층구조를 따라 올라가면서 루트 엘리먼트까지 이벤트가 전달되는 것을 말한다.

<div id="root" onclick="alert('one')">
  <button onclick="alert('two')"></button>
  <div onclick="alert('three')">
    <span onclick="alert('four')"></span>
  </div>
</div>

위 코드에서 span 태그를 클릭한다면?

 

 

 

 

four -> three -> one 알림창이 순서대로 뜨게된다.

 


이벤트 캡처링이란?

이벤트 버블링과 반대방향으로 이벤트가 전파되는것을 말한다.

예를 들어 아래와 같이 capture: true를 넣어주면 (true만 적어도 된다.) span 을 클릭했을때 capture! 알림 후 four, three, one 알림이 차례로 뜨게 된다.

const root = document.getElementById('root');
root.addEventListener('click', function(){
  alert('capture');
}, {capture: true});

vue 이벤트 수식어 capture를 사용한다면 아래와 같이 변경할 수 있다.

<div @click.capture="alert('one')">
  <button @click="alert('two')"></button>
  <div @click="alert('three')">
  	<span @click="alert('four')"></span>
  </div>
</div>

span을 클릭했을 경우 최상위 div에 capture가 걸려있기 때문에 one부터 이벤트가 실행되고 span부터 다시 위로 올라가게 된다.

따라서 결과는 'one' -> 'four' -> 'three'

 

이벤트 전파를 중단하는 방법은?

const span = document.getElementById('span');
span.addEventListener('click', function(event){
  event.stopPropagation();
});

만약 span을 클릭했을때 버블링 되는 현상을 막고싶다면? 위와 같이 stopPropagation() 함수를 넣어주면 span을 클릭했을때 'four' 알림창 밖에 뜨지 않는다.

vue 이벤트 수식어 stop을 사용한다면 아래와 같이 변경할 수 있다.

<div @click="alert('one')">
  <button @click="alert('two')"></button>
  <div @click="alert('three')">
  	<span @click.stop="alert('four')"></span>
  </div>
</div>

 

 

 

 

'기록' 카테고리의 다른 글

크롬에서 프린트시 배경색이 나오도록 하기  (0) 2020.09.16
mark tag  (0) 2020.09.15
모듈시스템  (0) 2020.08.24
ol counter  (0) 2020.08.12
Javascript 호출스택  (0) 2020.08.09