Custom Event를 만들어 보자!

MoonEn·2023년 2월 5일
0

JavaScript

목록 보기
3/5

JavaScript 과제를 진행하던 중, Custome Event를 만들어서 사용해야 하는 부분이 있었다. Custom Event라는 것을 처음 들어서 어떻게 사용하는지 공부하는 겸 블로그를 작성한다.

Custom Event

개념

Custom Evnet는 기본적으로 지원되는 이벤트(click, keydown, mouseover)가 아닌 개발자가 직접 생성하여 사용하는 이벤트이다.

생성 방법

Custom Event를 생성하는 법으로는 Custom Event 생성자를 사용하는 방법과 Event 생성자를 사용하는 방법이 있다.

Custom Evnet 생성자

const customEvent = new CustomEvent("customEvent", {
	detail: {
    	text: "Custom Event입니다!"
    }

new CustomEvent(typeArg, options)로 Custom Event를 생성한다. typeArg 매개 변수는 Event의 이름을 나타내는 문자열을 전달하고, options에는 detail과 Event 생성자의 옵션에 지정할 수 있는 속성(bubbles)을 지정할 수 있다. detail은 이벤트 세부 정보를 나타내는 값이다.

document.dispatchEvent("customEvent")

그리고 dispatchEvent()메서드를 이용해서 지정된 요소에 이벤트를 발생 시킬 수 있다. 그래서 특정한 DOM에서 Custom Event를 사용하기 위해서는 다음과 같이 쓸 수 있다.

HTML

<button id="myButton">Click me</button>

JavaScript

const myButton = document.querySelector('#myButton');
const customEvent = new CustomEvent("customEvent", {
	detail: {
    	text: "Custom Event입니다!"
    	}
    })
myButton.addEventListener('customEvent', function(event) {
  console.log(event.detail.text);
});
myButton.addEventListener('click', function(event) {
  myButton.dispatchEvent(customEvent);
});

button 요소에 click이벤트와 customEvent를 추가하고, click이벤트 발생 시 dispatchcustomEvent가 발생하고, addEventListener로 추가한 customEvent가 동작한다. 그래서 detail 객체의 text가 출력된다. 아래에 간단히 정리해 보았다.

Event 생성자

CustomEvent 생성자와 동일하게 Event 생성자도로 Custom Event를 만들 수 있다.

const customEvent = new Event('customEvent');

이 이후의 사용은 앞서 설명한 CustomEvent 생성자로 생성한 Custom Event와 동일하다.

마무리

처음 Custom Event를 만들어서 사용하라고 했을 때, '어떻게 만들라는거야?' 라는 생각으로 막막했다. 나름 블로그로 정리하면서 어떻게 사용하는지 정리가 되었고, 이를 이용해서 과제도 해결할 수 있었다. 혹시나 나처럼 어떻게 하는지 모르는 사람은 이걸보고 사용할 수 있게 정리가 되었으면 좋겠다는 생각에 글을 썼다. 이 글이 유용하길 바라며 나는 다시 공부하러 간다.

profile
개발자를 꿈꾸는 직장인

0개의 댓글