과제에서 커스텀 이벤트와 관련된 내용이 있었다. 커스텀 이벤트 구현해본 건 처음이었고, 유용하게 쓰일 수 있을 것 같아 정리하고자 한다.
JS의 내장 이벤트(click, scroll 등)가 아닌 사용자가 생성한 이벤트로 Event 혹은 CustomEvent 생성자를 사용해 커스텀 이벤트를 만들 수 있다.
new Event(type, option);
type: 커스텀 이벤트 이름을 설정
option: bubbles, cancelable 등을 설정
option은 모두 기본 값이 false이고, 상세 내용은 아래와 같다.
bubbles: true로 설정시 이벤트가 버블링 됨
cancelable: true로 설정시 e.preventDefault()로 이벤트를 취소
composed: true로 설정시 이벤트를 shadow DOM레벨을 넘어, 표준 DOM으로 전파 단, bubbles: true로 설정해야한다.
isTrusted 속성으로 이벤트가 사용자에 의해 직접 발생한 것인지 아니면 스크립트에 의해 인위적으로 생성된 것인지를 구분할 수 있다.
<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', (event) => {
console.log('isTrusted:', event.isTrusted); // 출력: true
});
</script>
<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', (event) => {
console.log('isTrusted:', event.isTrusted); // 출력: false
});
// 인위적으로 이벤트 트리거
const event = new Event('click');
button.dispatchEvent(event);
</script>
isTrusted는 보안 목적으로 사용될 수 있다. 스크립트에서 발생시킨 이벤트를 구분함으로써 악성 스크립트가 임의로 중요한 UI 동작을 트리거하는 것을 방지할 수 있다.
new CustomEvent(type, option);
Event와 같은 인자를 가진다. Event와 다른 점은 option에서 detail option이 존재한다는 것이다.
detail: 이벤트 발생시 넘기고 싶은 정보를 담음
const event = new CustomEvent('myEvent', {
detail: { key: 'value' },
bubbles: true,
cancelable: true
});
Event 객체와 CustomEvent 객체 모두 dispatchEvent를 통해 이벤트를 등록할 수 있다.
document.dispatchEvent(event);