CodeGym /행동 /Frontend SELF KO /사용자 정의 이벤트

사용자 정의 이벤트

Frontend SELF KO
레벨 42 , 레슨 2
사용 가능

8.1 사용자 정의 이벤트 생성하기

사용자 정의 이벤트는 JavaScript에서 개발자들이 자신만의 이벤트를 생성하고 디스패치할 수 있게 해줘. 이게 애플리케이션의 다양한 부분 사이의 정보 전달과 상호작용에 유용하게 쓰일 수 있어. 사용자 정의 이벤트를 생성하고 사용함으로써 코드 구조와 유연성을 개선할 수 있고, 애플리케이션 상태 관리와 알림을 제공할 수 있어.

사용자 정의 이벤트를 생성하기 위해선 CustomEvent 생성자를 사용해. 이 생성자는 새로운 이벤트를 사용자 정의 가능 매개변수와 추가 데이터와 함께 생성할 수 있게 해주지.

문법:

    
      const event = new CustomEvent(type, {detail: additionalData});
    
  

여기서:

  • type: 이벤트의 이름을 나타내는 문자열
  • detail: 이벤트와 함께 전달될 추가 데이터를 담고 있는 객체

사용자 정의 이벤트 생성 예제:

JavaScript
    
      const myEvent = new CustomEvent('myCustomEvent', { detail: { message: 'Hello, world!' } });
    
  

8.2 사용자 정의 이벤트 디스패칭

이벤트 디스패칭은 dispatchEvent 메서드를 사용해. 이 메서드는 이벤트가 발생해야 할 요소에서 호출돼.

설명:

  • 이벤트 핸들러 myCustomEvent가 버튼 myButton에 추가되고, 이벤트의 데이터에서 메시지를 콘솔에 출력함
  • myCustomEvent라는 사용자 정의 이벤트가 detail에 메시지를 담고 생성됨
  • 이벤트가 myButton에 디스패치되어 핸들러를 호출하고 콘솔에 메시지를 출력함

예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Custom Event Example</title>
        </head>
        <body>
          <button id="myButton">Button</button>
          <script>
            const button = document.getElementById('myButton');

            // 사용자 정의 이벤트 핸들러 추가
            button.addEventListener('myCustomEvent', function(event) {
              console.log('Custom event received:', event.detail.message);
            });

            // 사용자 정의 이벤트 생성 및 디스패칭
            const myEvent = new CustomEvent('myCustomEvent', { detail: { message: 'Hello, world!' } });
            button.dispatchEvent(myEvent);
          </script>
        </body>
      </html>
    
  

8.3 사용자 정의 이벤트의 적용

사용자 정의 이벤트는 모듈화된 코드와 유지보수 가능한 코드를 작성하는 데 유용해, 특히 컴포넌트와 복잡한 애플리케이션을 다룰 때 더 그렇지. 한 컴포넌트가 이루어진 변화나 행동을 다른 컴포넌트에 알리는 데 사용할 수 있어.

설명:

  • 모듈 A가 notifyB 사용자 정의 이벤트를 moduleB 요소에 데이터와 함께 디스패치함
  • 모듈 B는 notifyB 이벤트를 듣고 처리하여 콘솔에 메시지를 출력함

모듈식 애플리케이션에서 사용자 정의 이벤트 사용하는 예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Module Communication Example</title>
        </head>
        <body>
          <div id="moduleA">Module A</div>
          <div id="moduleB">Module B</div>
          <script>
            const moduleA = document.getElementById('moduleA');
            const moduleB = document.getElementById('moduleB');

            // 모듈 A가 사용자 정의 이벤트를 디스패치함
            function notifyModuleB() {
              const event = new CustomEvent('notifyB', { detail: { message: 'Data from Module A' } });
              moduleB.dispatchEvent(event);
            }

            // 모듈 B가 사용자 정의 이벤트를 듣고 있음
            moduleB.addEventListener('notifyB', function(event) {
              console.log('Module B received:', event.detail.message);
            });

            // 모듈 A에서의 행동 시뮬레이션
            notifyModuleB();
          </script>
        </body>
      </html>
    
  

8.4 사용자 정의 이벤트의 매개변수

사용자 정의 이벤트는 다음 매개변수를 통해 추가로 설정할 수 있어:

  • bubbles: 이벤트가 버블링되어야 하는지를 나타내는 논리값. 기본값은 false
  • cancelable: 이벤트를 취소할 수 있는지를 나타내는 논리값. 기본값은 false
  • composed: 이벤트가 Shadow DOM을 넘어 전파되어야 하는지를 나타내는 논리값. 기본값은 false

예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Custom Event Parameters Example</title>
        </head>
        <body>
          <div id="container">
            <button id="myButton">Button</button>
          </div>
          <script>
            const container = document.getElementById('container');
            const button = document.getElementById('myButton');

            // 컨테이너와 버튼에 핸들러 추가
            container.addEventListener('customEvent', function(event) {
              console.log('Container received:', event.detail.message);
            });

            button.addEventListener('customEvent', function(event) {
              console.log('Button received:', event.detail.message);
            });

            // 매개변수로 사용자 정의 이벤트 생성 및 디스패칭
            const myEvent = new CustomEvent('customEvent', {
              detail: { message: 'Hello from button' },
              bubbles: true,
              cancelable: true,
              composed: false
            });

            button.dispatchEvent(myEvent);
          </script>
        </body>
      </html>
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION