JS/JS 핵심 개념

JS 이벤트 위임

spare8433 2023. 3. 14. 19:07

이벤트 위임 (delegate)

이벤트 흐름을 활용하여 이벤트를 발생시키고 싶은 요소를 이벤트 리스너가 설치된 부모 요소의 자식으로 배치하여 단일 이벤트 리스너가 여러개의 이벤트 대상을 처리할 수 있게 하는 프로그래밍을 이벤트 위임이라 한다.


이벤트 리스너의 event 객체에는 돔에서 일어나는 이벤트의 정보가 들어있다



event.currentTarget : 이벤트가 등록된 요소를 의미
this : 이벤트 리스너안의 thisevent.currentTarget 가 참조하는 대상과 같다
event.target : 이벤트가 최초에 발생한 요소를 의미



<div class="parent">
  <button type="button">generate item</button>
  <ul>
    <li>initial item</li>
  </ul>
</div>

<script>
  var parent = document.querySelector(".parent");
  parent.addEventListener('click', function (event) {
    if (event.target.tagName.toLowerCase() === "button") {
      const item = document.createElement("li");
      item.innerText = "hello world~";
      parent.querySelector("ul").appendChild(item);
    }

    if (event.target.tagName.toLowerCase() === "li") {
      console.log('hit!!');
    };
  });
</script>

참고

https://www.inflearn.com/course/%EC%BD%94%EB%94%A9%EC%9D%B8%ED%84%B0%EB%B7%B0-js-%EC%96%91%EC%84%B1%ED%95%99%EA%B5%90