dispatchEvent 메서드
dispatchEvent 메서드를 사용하면 요소에서
이벤트를 시뮬레이션할 수 있습니다.
이것이 필요한 이유: 사용자의 버튼 클릭,
폼 제출 시도 등을 모방할 수 있습니다. 이때
이벤트는 event.isTrusted 속성을
제외하고는 실제 이벤트와 아무런 차이가 없습니다.
비표준(직접 만든) 이름을 가진 이벤트를 생성한 후
필요한 순간에 호출하는 것도 가능합니다. 이 메서드는 이벤트를 발생시켜야 할 요소에 적용됩니다.
매개변수로는 생성자
new Event로 생성된 이벤트(객체)를 받습니다.
구문
요소.dispatchEvent(이벤트);
예시
버튼이 있다고 가정해 봅시다. 이 버튼을 클릭하면 메시지가 출력됩니다. 마우스를 버튼 위에 올렸을 때 버튼이 클릭된 것으로 인식하도록 만들어 봅시다:
<button id="button">button</button>
let button = document.querySelector('#button');
button.addEventListener('click', function() {
alert('message');
});
button.addEventListener('mouseover', function() {
let clickEvent = new Event('click'); // 이벤트 생성
this.dispatchEvent(clickEvent); // 버튼 클릭 시뮬레이션
});
:
예시
자신만의 이벤트(자신만의 이름으로)를 생성한 후
필요한 순간에 호출할 수 있습니다. 버튼에
showMessage 이벤트를 연결하고 마우스를 올렸을 때
이 이벤트를 발생시켜 봅시다:
<button id="button">버튼</button>
let button = document.querySelector('#button');
button.addEventListener('showMessage', function() {
alert('message');
});
button.addEventListener('mouseover', function() {
let showMessageEvent = new Event('showMessage'); // 이벤트 생성
this.dispatchEvent(showMessageEvent); // 이벤트 발생
});
: