Notice
Recent Posts
Recent Comments
Link
Little Jay
[JS] Event Delegation 본문
질문 출처: https://www.frontendinterviewhandbook.com/javascript-questions#explain-event-delegation
JavaScript trivia questions in front end interviews | Front End Interview Handbook
Answers to Front-end Job Interview Questions - JS Questions. Pull requests for suggestions and corrections are welcome!
www.frontendinterviewhandbook.com
이벤트 위임
이벤트 위임이라고 하는 것은 부모 요소에 이벤트를 등록해서 하위의 자식 요소들을 제어하는 방식이다.
이벤트 위임을 사용하면 요소마다 핸들러를 할당하지 않고, 요소의 공통 조상에 이벤트 핸들러를 단 하나만 할당해도 여러 요소를 한꺼번에 다룰 수 있다. 이벤트는 Bubbling된다는 특성이 있다. 따라서 부모요소에 이벤트를 등록함으로서 이벤트가 자식 요소들에게 Propagate되어 한 번에 핸들링할 수 있다.
이벤트 위임의 장점
- 첫 번째로 메모리와 코드의 길이적인 측면에서 이점이 있다. 예를 들어 Table같은 요소의 <td>가 9개가 있다고 한다면 일일이 각각의 td에 이벤트를 등록하는 것이 아닌, table에 이벤트를 등록함으로서 메모리적인 측면과 코드의 간결성을 유지할 수 있다.
- 동적으로 자식요소들을 추가한다면 이미 만들어지지 않은 요소들에도 충분히 Event가 Bubbling되어 자식요소에도 동작한다. 이는 Element를 Create할 때뿐만 아니라 Remove할때도 작동한다.
이벤트 위임의 단점
- 이벤트 위임을 사용하려면 이벤트가 반드시 버블링 되어야 합니다. 하지만 몇몇 이벤트는 버블링 되지 않는다. 그리고 낮은 레벨에 할당한 핸들러엔 event.stopPropagation()를 쓸 수 없다.
- 이벤트 위임은 모든 하위 컨테이너에서 발생하는 이벤트에 응답해야 하므로 CPU 작업 부하가 늘어날 수 있다. 그런데 이런 부하는 무시할만한 수준이므로 실제로는 잘 고려하지 않는다.
예시

<body>
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
<button>Next Num</button>
</body>
<script>
const list = document.querySelector("ol");
const lists = document.querySelectorAll("li");
list.addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
window.alert(e.target.innerText);
}
});
const btn = document.querySelector("button");
btn.addEventListener("click", (e) => {
const nextLi = document.createElement("li");
nextLi.innerText = "Next Level";
list.appendChild(nextLi);
});
</script>
Reference
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Building_blocks/Events
'FrontEnd > Front End Interview Handbook' 카테고리의 다른 글
| [JS] IIFE를 올바르게 동작하는 방식에 대하여 (0) | 2023.03.06 |
|---|---|
| [JS] Prototype 상속은 어떻게 이루어지는가 (0) | 2023.01.26 |
| [JS] Javascript에서의 this 규칙 (0) | 2022.12.28 |
Comments