이벤트 위임이 생긴 배경
자바스크립트에서는 페이지에 존재하는 이벤트 핸들러의 개수가 페이지 성능에 직접적으로 영향을 미친다.
그 이유는 첫번째로는 각 함수가 메모리를 점유하는 객체여서이고,
두번째는 이벤트 핸들러를 많이 할당하려면 DOM 접근도 많아지며 이는 전체 페이지의 응답성을 떨어트린다.
그러므로 이벤트 위임을 사용한다.
이벤트 위임이란?
DOM 트리에서 가능한 가장 높은 요소에 이벤트 핸들러를 단 하나만 할당하여 해당 타입의 이벤트를 처리하는 기법이다.
이벤트 핸들러의 개수를 줄이기 위해 사용한다.
click 이벤트는 document 레벨까지 버블링되어 올라간다. 즉 클릭 가능한 요소마다 일일이 onclick 이벤트 핸들러를 할당하지 않고 전체 페이지에 하나만 할당해도 된다.
다음 예제를 보자.
<ul id="myLinks">
<li id="goSomewhere">Go somewhere</li>
<li id="goanywhere">Go anywhere</li>
<li id="sayHi">say hi</li>
</ul>
const item1 = document.getElementById("goSomewhere");
const item2 = document.getElementById("goanywhere");
const item3 = document.getElementById("sayHi");
item1.addEventListener("click", function(event){
location.href="https://www.naver.com/";
}, false);
item2.addEventListener("click", function(event){
document.title = "I changed the document's title";
}, false);
item3.addEventListener("click", function(event){
console.log("hi");
}, false);
이 예제는 클릭에 반응해야 할 항목이 세개가 있다. 고전적이고 단순하게 이벤트 핸들러를 할당했다.
이벤트 핸들러를 적용할 경우
const list = document.getElementById("myLinks");
const clickActions = {
goSomewhere: () => location.href = "https://www.naver.com/",
goanywhere: () => document.title = "I changed the document's title",
sayHi: () => console.log("hi"),
}
list.addEventListener("click", e => {
const action = e.target.id;
if(action) {
clickActions[action]();
}
});
이렇게 사용할 수 있다.
'개발 > JavaScript' 카테고리의 다른 글
[Javascript] plain DB 데이터로 Tree 쉽게 만들기 (0) | 2022.04.14 |
---|---|
[Javascript] Method Chaining 메서드 체이닝 (0) | 2022.04.12 |
[Vanilla Javascript] Jasmine을 이용해 테스트 코드 작성해보기 -3 (0) | 2022.04.10 |
[Vanilla Javascript] Jasmine을 이용해 테스트 코드 작성해보기 -2 (0) | 2022.04.10 |
[Vanilla Javascript] Jasmine을 이용해 테스트 코드 작성해보기 -1 (0) | 2022.04.10 |