완로그
article thumbnail

⏳ 2023. 5. 22. - 2023. 5. 28.

 

1. 이벤트 객체

이벤트 객체는 대상에서 발생한 이벤트 정보를 담고 있다.


2. 버블링과 캡처링

  1. 캡처링 단계 : 이벤트가 하위 요소로 전달
  2. 타깃 단계 : 이벤트가 실제 타깃 요소로 전달
  3. 버블링 단계 : 이벤트가 상위 요소로 전파

3. 이벤트 옵션

<javascript />
const parent = document.querySelector(".parent"); const child = document.querySelector(".child"); // 핸들러를 한 번만 실행 child.addEventListener( "click", () => { console.log("I'm gone"); }, { once: true, } ); // 기본 동작과 핸들러 실행을 분리 parent.addEventListener( "wheel", () => { for (let i = 0; i < 10000; i++) { console.log(i); } }, { passive: true, } );

4. 이벤트 위임

비슷한 패턴의 여러 요소에서 이벤트를 핸들링해야 하는 경우,

단일 조상 요소에서 제어하는 이벤트 위임 패턴을 사용할 수 있다.

<javascript />
// 이벤트 위임(Delegation) const parent = document.querySelector(".parent"); const childs = document.querySelectorAll(".child"); // 모든 대상 요소에 이벤트 등록 // childs.forEach((child) => { // child.addEventListener("click", (e) => { // console.log(e.target.textContent); // }); // }); // 조상 요소에 이벤트 위임 parent.addEventListener("click", (e) => { const el = e.target.closest(".child"); if (el) { console.log(el.textContent); } });

5. 키보드 이벤트

<javascript />
const input = document.querySelector("input"); input.addEventListener("keydown", (e) => { if (e.key === "Enter") { console.log(e.target.value); } });

CJK 문자를 입력한 경우, 브라우저에서 문자를 처리하는 과정을 거쳐 2번의 이벤트가 발생한다.

 

한글은 모음과 자음으로 한 음절이 만들어지는 조합문자이다.

isComposing은 입력된 문자가 조합된 문자인지 아닌지 판별하는 함수로,

값을 호출해보면 첫 번째 값은 true, 두 번째 값은 false로 출력된다.

글자가 조합되는 과정에 발생하는 이벤트는 무시하고

조합이 끝나고 발생하는 이벤트에 대해서만 처리하기 위해 다음과 같이 코드를 작성할 수 있다.

<javascript />
const input = document.querySelector("input"); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { console.log(e.target.value); } });


6. 커스텀 이벤트

<javascript />
// 커스텀 이벤트와 디스패치 const c1 = document.querySelector(".child:nth-child(1)"); const c2 = document.querySelector(".child:nth-child(2)"); c1.addEventListener("click", () => { // 이벤트 강제 발생 c2.dispatchEvent(new Event("click")); c2.dispatchEvent(new Event("wheel")); c2.dispatchEvent(new Event("keydown")); }); c2.addEventListener("click", () => { console.log("Child2 click!"); }); c2.addEventListener("wheel", () => { console.log("Child2 wheel~"); }); c2.addEventListener("keydown", () => { console.log("Child2 keydown."); });

직접적인 이벤트가 발생하지 않더라도, dispatchEvent를 통해 이벤트를 생성하고, 발생시킬 수 있다.

 

이를 이용하여 이벤트를 커스터마이즈할 수 있다.

<javascript />
c1.addEventListener("click", () => { // 커스텀 이벤트 c2.dispatchEvent(new Event("hello-world")); }); c2.addEventListener("hello-world", () => { console.log("Child2 hello, world!!"); });

 

데이터를 전달하고 싶을 때는 detail을 사용하자.

<javascript />
c1.addEventListener("click", () => { // 커스텀 이벤트 c2.dispatchEvent( new CustomEvent("hello-world", { detail: 123, }) ); }); c2.addEventListener("hello-world", (e) => { console.log("Child2 hello, world!!"); console.log(e.detail); });
profile

완로그

@완석이

프론트엔드 개발자를 꿈꾸는 완석이의 일기장입니다.