본문으로 바로가기

이번 글에서는 이벤트 위임에 대해서 알아보자

우선 결과물 모습 부터 보자.

 

 

 

 

아래와 같은 html 코드가 있을 때, 클릭 되는 대상에게 active 클래스를 붙여주고 기존에 active 클래스를 가지고 있는 대상은 active 클래스를 지워주는 방식으로 구현을 하면 된다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      .active{
        color : red;
      }
    </style>
  </head>
  <body>
    <h1 id="main-title"> DOM (Document Object Model)</h1>
    <ul class="fruit-list">
      <li class="fruit">apple</li>
      <li class="fruit">banana</li>
      <li class="fruit">melon</li>
    </ul>
  </body>
</html>
 
cs

 

이때 각 li 들은 ul의 하위 태그들 이므로 ul을 가져와서 for문을 이용해서 접근하여 직접 이벤트 처리를 할 수 도있다.

하지만 모든 이벤트를 감지 할 수 있는 부모 태그인 ul에게 이벤트 리스너를 추가해주고 e.target을 통해서 li들 마다 이벤트가 처리 되는 것 처럼 할 수 있다. 즉 부모 태그에게 이벤트를 위임하는 방식이다. script 코드는 아래와 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <script>
      var currentFruit;
      var fruits = document.querySelector('.fruit-list')
 
      function clickHandler(e){
        if(currentFruit){
          currentFruit.classList.remove('active')
        }
        e.target.classList.add('active');
        currentFruit = e.target;
      }
 
      fruits.addEventListener('click', clickHandler);
    </script>
cs

 

이벤트 핸들러는 부모태그인 ul에 추가해줬지만 해당 li를 클릭하면 ul이 해당 이벤트를 감지하고 해당 이벤트 핸들러 내에서 e.target을 통해서 클릭된 li를 접근하여 active 클래스를 추가해주면 된다. 또 currentFruit로 이전 선택된 li를 저장해 놓은뒤 classList를 조작해주는 방식으로 이전 대상의 active를 지워준다. 

 

 

e.currentTaget 과 this는 ul을 가리키고

e.target은 해당 li을 가리킨다.