JSTS
[JS] 이벤트 위임 적용해보기 event delegation
Jaaaay
2022. 8. 20. 17:06
이벤트 위임
function clickHandler(e) {
this.parentNode.removeChild(this);
}
for (let i = 0; i < ilbuniGroup.length; i++) {
ilbuniGroup[i].addEventListener("click", clickHandler);
}
이벤트를 각각 등록해주는 것은 객체 길이가 많아질 경우 비효율적이다.
부모 컴포넌트에 이벤트를 위임한다.
const stage = document.querySelector(".stage");
function clickHandler(e) {
if (e.target.classList.contains("ilbuni")) {
stage.removeChild(e.target);
}
}
stage.addEventListener("click", clickHandler);
- 클릭할 컴포넌트 내부에 여러 자식 컴포넌트가 있을 경우
1. 자식 요소에 pointer-events: none 을 주어 해결 가능
→ 내부 요소를 사용해야할 경우 부적절
2.script에 while문을 통해 부모에 원하는 요소가 있는지 조사
→ 코드가 조금 복잡해질 수 있음
function clickHandler(event) {
let elem = event.target;
while (!elem.classList.contains('menu-btn')){
elem = elem.parentNode;
if(elem.nodeName = 'BODY'{
elem = null;
return;
}
}
더 알아보기
https://github.com/baeharam/Must-Know-About-Frontend/blob/main/Notes/javascript/event-delegation.md