[자바스크립트] 이벤트 제어 방법 – event 키워드

아래의 예제는 버튼을 클릭한 때 일어난 이벤트의 타입을 출력한다. click이라고 나온다.

<button onclick="testFunction(event)">test button</button>

<script>
    function testFunction(e)
    {
        e.target.innerHTML = e.type;
    }
</script>

위의 코드는 간단하지만 낯설다. event 아규먼트가 뭔지 애매하다. 다른 이름으로 바꾸면 위의 코드는 작동하지 않으므로 예약된 키워드인 거 같지만 아니다. 자바스크립트 레퍼런스에 event라는 키워드는 명시되어 있지 않다. 이건 웹브라우저가 처리하는 키워드다.

위의 방법은 직관적이어서 좋지만 자바스크립트에 충실하지 않고 관리하기 편하지도 않으므로 쓰지 않는 게 좋다.

It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient.
Introduction to events

아래와 같이 EventListener를 이용하는 게 좋다.

<button>test button</button>

<script>
    function testFunction(e)
    {
        e.target.innerHTML = e.type;
    }
    
    document.addEventListener("click", function(e) { testFunction(e) } );
</script>