frontend - (7) : Event flow

­이승환·2021년 9월 30일
0

Frontend

목록 보기
7/8

Event flow


자바스크립트를 이용해서 Dom 을 조작하는 것은 많은 프론트엔드 개발자에게 필수이다. 일반적인 웹 페이지에서 Dom의 존재 이유는 어쩌면 이벤트를 다루기 위함이라고 생각한다. Dom은 일반적으로 트리구조로 구성되어있고, 자세히 설명하지는 않겠다.
브라우저 위에 겹겹이 쌓여있는 Dom들의 경우 EventListener를 추가했을 때 Event 가 propagation(전파) 된다. 이번 포스팅을 통해서 어떻게 이벤트 들이 전파되는 지 정리해보고자 하고 실제 활용사례들을 언급해보고자 한다.

keyword

  1. Event Bubble
  2. Event Capturing
  3. DOM Event flow

1. Event Bubble

화면에 특정 Element에서 이벤트가 발생하였을 때, 상위 Element로 이벤트가 전파해 나가는 것을 Event Bubbled이라고 한다.

<html>
	<head>
   	<title>......</title>
 	</head>
   <body>
   	<div id="test">button</div>
   </body>
</html>

위와 같은 .html 파일에서 <div>가 클릭되었을 때, 이벤트 발생 순서는 아래와 같다.

(1) div
(2) body
(3) html
(4) document

2. Event Capturing

Event Bubble과 반대방향으로 이벤트가 발생하는 것을 Event Capturing이라고 한다.

위의 예제를 이용해서 설명하면 순서는 아래와 같다.

(1) document
(2) html
(3) body
(4) div

3. DOM Event Flow

표준 DOM Events에서 이벤트의 전파는 3단계로 이루어져있다.
1. Capturing phase : the event goes up to the element
2. Target phase : event reached the target element
3. Bubbling phase : the event bubbles down from the element

하지만 실제로 세단계가 전부 이루어지지 않고 , 1 + 2 또는 2 + 3 로 구성되어 일어난다.

예제 코드는 아래와 같다.

<!DOCTYPE html>
<html>
  <head>
    <title>Example: Setting Event Handling using DOM</title>
    <style type="text/css">
      html {
        background-color: #fff;
      }
      body {
        font-family: Verdana;
        background: #7e7e;
        color: #fff;
        padding: 10px;
        border: 4px solid #555;
      }
      p {
        font-family: Verdana;
        background: #fa8b7c;
        color: #fff;
        padding: 10px;
        border: 4px solid #555;
      }
    </style>
  </head>
  <body>
    body tag
    <p>
      p tag
    </p>
  </body>

  <script>
    for (let elem of document.querySelectorAll('*')) {
      elem.addEventListener(
        'click',
        e => console.log(`Capturing: ${elem.tagName}`),
        true
      )
      elem.addEventListener('click', e =>
        console.log(`Bubbling: ${elem.tagName}`)
      )
    }
  </script>
</html>

addEventListener 함수의 3번째 파라미터에 true값을 주면 capturing, false(default)를 주면 bubble이 발생한다.

실제 활용 사례

지도앱을 직접 만든다고 생각해보자. 일반적인 네이버 지도나 카카오 지도를 찾아보면 canvas에 지도 이미지를 붙이고 <span> 태그로 위치를 표시한다. 구성되어있는 여러 옵션들을 클릭하면 canvas위에 여러가지 Element들이 덕지 덕지 붙는다. 여기서 만일 canvas parent Element에 자손 Element를 생성한다면.. 이벤트 버블이 발생할 것이다. 따라서 클릭 이벤트 활용시에 event.stopPropagation() 함수로 버블링을 막아줘야 한다.

profile
Mechanical & Computer Science

0개의 댓글