new Event 명령어
new Event 명령어는 이벤트 생성자로,
이를 사용하여 이벤트 객체를 생성한 후
dispatchEvent 메서드를 사용해
JavaScript에서 이 이벤트를 발생시킬 수 있습니다.
이것이 필요한 이유는 사용자의 버튼 클릭,
폼 제출 시도 등을 모방할 수 있기 때문입니다.
이 경우 생성된 이벤트는
event.isTrusted 속성을 제외하고는
실제 이벤트와 아무런 차이가 없습니다.
비표준(사용자가 만든) 이름을 가진 이벤트를 생성하고
필요한 순간에 이를 발생시킬 수도 있습니다.
구문
new Event(이벤트 타입, [플래그]);
예시
버튼이 있다고 가정해 봅시다. 이 버튼을 클릭하면 메시지가 출력됩니다. 마우스를 버튼 위로 가져가면 버튼이 클릭된 것으로 인식되도록 만들어 봅시다:
<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</button>
let button = document.querySelector('#button');
button.addEventListener('showMessage', function() {
alert('message');
});
button.addEventListener('mouseover', function() {
let showMessageEvent = new Event('showMessage'); // 이벤트 생성
this.dispatchEvent(showMessageEvent); // 이벤트 발생
});
:
함께 보기
-
이벤트를 연결하는 속성
addEventListener -
이벤트 연결을 해제하는 속성
removeEventListener