JavaScript - 이벤트 리스너 및 핸들러

안녕하세요 여러분 👋 JavaScript의 이벤트 처리에 대해 이야기해 봅시다.

내용의 테이블


  • Introduction
  • Event Listener and Event Handler
  • Capture and Bubbling
  • Example

  • 소개

    When I started learning JavaScript (JS), I read somewhere that JS is an event-driven programming language, and that the use of JS in the browser was to add interactivity to the web pages.

    But what are events in JS? Well, events are just actions that happen when the user is accessing the web pages and it could be the loading of the document, the fetching of data, the clicking of elements inside the document, the pressing of keys or touchscreen and many more.

    These actions are known as events in JS and we can respond to these events by calling functions and manipulate the DOM to provide that interactivity and feedback to the user.

    이벤트 리스너 및 이벤트 핸들러

    Imagine you have a button, and you would like to know when the user has clicked this button so that you can run a block of code. You can attach an event listener to any element you would like to "listen" for an event type by using .addEventListener() . This method typically takes two parameters, the first being the event type you would like to listen out for (as a string) and the second is the callback function you would like to run when the event occurs (sometime referred to as "fires"). The function that runs when the event "fires" is sometimes called the event handler.

    Typically, you would grab the element from the HTML DOM by using something like document.getElementById() or document.querySelector() . I like to use the .querySelector because it feels easier since it is the same selector as CSS.

    const button = document.querySelector("button");
    button.addEventListener("click", (e)=> {
       // some code to manipulate the DOM here
    });
    

    You may notice that in the example, the anonymous function takes in an argument e . This argument is the event object, it is an object which contains details about the event that occurred so you can capture things like the target of the event, or the coordinate of the cursor, etc.

    You can attach more than one event listener to an element and if they are the same type, the callback function will run in the order the event listener was defined.

    There is also another way to apply event listener to an element, and that is setting the event handler property to a function to handle that event. For example, buttton.onclick = doMagic but by adding event listener this way you can only add one handler.

    캡처 및 버블 단계

    Sometimes, you may have an event listener on the parent element but not on the child, or you have it for both. So, to deal with nested elements situation and when each event handler will run, you need to be aware of the Capture phase and the Bubble phase. "Bubbling" means that the event "propagate", aka move up and outward from the inner most element all the way to the <html> element. And "Capturing" is the opposite, the browser will call the event handler for the outer most element ( <html> ) down to the inner most element.

    The Capture phase always gets called before the Bubble phase, which means that any element with the event listener set to use capture will fire before all element set with bubble. To use capture, we shall return to .addEventListener() , you can add a third argument when attaching the event listener { capture: true } .



    예시

    I have made something silly with the codepen below. I used window.onload event handler property to make bubbles show up on the screen once the window has loaded. I added an event listener to each bubble so upon mouse entering the element, the bubble would disappear. I also added a small example of capturing and bubbling at the bottom of the JS file, console logging some words when the element is clicked. You can see the code snippet below, take a guess what the console will log, then click anywhere on the screen and check the console to see if you were correct 😀. Note: canvas is the variable name holding the <main> element of the page.

    
    function sparkle() {
      console.log("sparkle");
    }
    
    function sparkleTwice() {
      console.log("sparkle, sparkle");
    }
    
    function dazzle() {
      console.log("dazzle");
    }
    
    document.addEventListener("click", sparkle, {capture: true});
    document.addEventListener("click", sparkleTwice)
    canvas.addEventListener("click", dazzle);
    
    

    요약



    따라서 모든 것을 요약하면 특정 작업, 이벤트를 수신하려는 경우 이벤트 리스너를 요소에 연결할 수 있습니다. 이벤트가 발생하면 이벤트 리스너는 이벤트 핸들러를 호출합니다. 콜백 함수는 이벤트 객체를 매개변수로 사용하고 코드 블록을 실행합니다. 중첩된 요소가 있는 경우 이제 버블링으로 인해 이벤트가 전파되므로 이벤트 리스너에서 이상한 동작이나 문제를 발견하면 이것이 그 이유일 수 있습니다. 캡처를 사용하여 특정 순서로 이벤트 핸들러를 트리거하는 방법도 알고 있습니다.

    나는 개념을 이해하는 가장 좋은 방법은 거기에 나가서 무언가를 구현하려고 노력하는 것이라고 믿습니다. 시작점이 필요하면 내 코드를 깨고, 이벤트 리스너를 더 추가하고, 기능을 변경하고, 가지고 놀 수 있습니다. 아니면 처음부터 직접 만드세요! 😀

    읽어주셔서 감사합니다. 의견이나 의견이 있으시면 아래에 남겨주세요.

    좋은 웹페이지 즐겨찾기