[TIL / JavaScript] event.target, 이벤트 위임

Changyun Go·2021년 12월 11일
2
post-thumbnail

[TIL / JavaScript] event.target, 이벤트 위임

  • 이벤트가 일어날 객체를 말한다. → 버튼을 눌러 새로운 창이 열리는 객체가 있다면, 여기서 버튼이 event target이다.

이벤트 발생 과정


  1. 지정된 event target(html 요소)에
  2. 지정된 event type(클릭이나 스크롤 등)이 발생하면
  3. 지정된 event handler(함수)가 실행된다.

event target에서 얻을 수 있는 속성 값


  • 다른 프로퍼티와 조합하여 현재 이벤트가 발생한 요소의 속성 값을 얻을 수 있다.
<div id="nulbo">늘보<div>

위와 같은 객체를

let t = document.getElementById("nulbo");
t.addEventListener("click", function(event){
        alert("안녕 늘보");
    });

마우스로 클릭했을 때 이벤트가 일어나는 event target으로 지정해주었다.

tagName

console.log(event.target.tagName); // div

id

console.log(event.target.id); // nulbo

textContent

console.log(event.target.textContent); // 늘보

이 밖에도 다양한 속성 값을 얻을 수 있다.

이벤트 위임


  • 캡처링과 버블링을 활용하여 이벤트 위임을 구현할 수 있다.
  • 요소마다 핸들러를 할당하지 않고, 요소의 공통 조상에 이벤트 핸들러를 하나만 할당해도 여러 요소를 한꺼번에 다룰 수 있다.
<table>
  <tr>
    <th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
  </tr>
  <tr>
    <td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders</td>
    <td class="n">...</td>
    <td class="ne">...</td>
  </tr>
  <tr>...2 more lines of this kind...</tr>
  <tr>...2 more lines of this kind...</tr>
</table>

위와 같이 9개의 칸이 있는 테이블이 있을 때

table 요소.onclick = function(event) {
	// TD에서 발생한 게 아니라면 아무 작업도 하지 않는다,
	if (event.target.tagName != 'TD') return; 
  console.log(event.target.textContent); // event target의 텍스트를 출력한다.
};

각 <td>마다 onclick 핸들러를 할당하는 대신 <table> 요소에 할당하여 원하는 동작을 구현할 수 있다.

<td>
  <strong>Northwest</strong>
  ...
</td>

하지만 <td>안에 중첩 태그 <strong>이 있어 버그가 발생할 수 있다.

closest()

  • 선택된 요소의 상위 요소 중 selector와 일치하는 가장 근접한 조상 요소를 반환한다.
var closestElement = targetElement.closest(*selectors*);

closest 메소드를 이용하여 중첩 태그 <strong>이 선택되더라도 <td>를 찾을 수 있다.

table.onclick = function(event) {
  let td = event.target.closest('td');
  if (!td) return;
  if (!table.contains(td)) return;
  console.log(event.target.textContent);
};

P.S

✍️ 이번 미니프로젝트에 event target을 사용하면서 이벤트에 대해 다시 한번 찾아보는 기회를 가질 수 있었다🙂 만약 event target 속성과 이벤트 위임이라는 특성이 없었다면 일일이 달력 칸마다 input을 만들어야 할 수도 있었다는 생각에 아찔하다😨

Reference


0개의 댓글