이벤트 위임 (event delegation)

딱이·2021년 4월 20일
0

언제 쓰는거죠❔

: 비슷한 방식으로 여러 요소를 다뤄야 할 때 사용함.
이벤트 위임을 사용하면 요소마다 handler를 할당하지 않고, 요소의 공통 부모 요소에 event handler를 한번만 할당해도 여러 요소를 한번에 다룰수 있음. (feat. 반복문, 부모요소..)

사용예제

[html]
<ul>
	<li>a</li>
	<li>b</li>
</ul>

[js]

// 반복문을 통한 이벤트 위임
const $li = document.querySelectorAll("ul > li");

for (let i = 0; i < $li.length; i++) {
	$li[i].addEventListener("click", (event) => {
    	console.log(event.currentTarget.textContent);
    })
}

// 공통의 부모요소를 통한 이벤트 위임
ul.addEventListener("click",function(evt) {
	const liText = evt.currentTarget.firstElementChild().textContent;
    	console.log(liText);
});

event.target

: 클릭한 부분의 요소

event.currentTarget

: 이벤트 할당한 요소

$.firstChild()

: 첫번째 객체 가져오기

$.firstElementChild()

: 첫번째 노드 객체 가져오기.
한번씩 firstChild가 보이지 않는 객체를 가져올때가 있음.

$.tagName

: 객체 타입 이름 가져오기

ex )

$input.tagName(); 	// input

[참고] https://ko.javascript.info/event-delegation

profile
뚝딱뚝딱 FE

0개의 댓글