Deep Dive - 40.이벤트 위임

Jihyun-Jeon·2022년 5월 11일
0

Javascript - Deep Dive

목록 보기
16/26
post-thumbnail

🔶 이벤트 위임

여러 개의 하위 DOM 요소에 각각 이벤트를 등록하는게 아니라, 하나의 상위 DOM요소에 이벤트를 등록하는 방법

  • 작동 원리
    : 버블링을 통해 이벤트 타켓(이벤트를 발생시킨 DOM요소)에서 부터 상위 요소로 올라가면서 이벤트를 캐치하게 됨.

  • 만약 하위 요소에 각각 이벤트 핸들러를 등록한다면?
    : 성능 저하, 유지 보수가 어려운 단점 발생함.

  • 주의
    : 이벤트 위임을 통해 상위 DOM요소에 이벤트를 바인딩한 경우, 이벤트target과 currentTarget이 다른 DOM요소라는 것!

  • 코드 예제
    : 모든 button요소에 각각 이벤트를 걸지 않고, 상위 요소인 div에만 걸음
    : 모든 button요소 클릭시 이벤트 실행됨.
<body>
    <div id="wrapper">
      <button>1</button>
      <button>2</button>
      <button id="three">3</button>
      <button>4</button>
      <button>5</button>
    </div>
    <script>
      const wrapper = document.querySelector('#wrapper');
      wrapper.addEventListener('click', () => console.log('clicked!'));
    </script>
  </body>

🔶 이벤트 전파 방지

Event.stopPropagation()

: 이벤트가 캡처링/버블링 단계에서 더 이상 전파되지 않도록 이벤트 전파를 방지함.

예제 - 3번 버튼에 stopPropagation메서드를 걸음

3번 버튼 자신이 발생시킨 이벤트가 전파되는 것을 중단하여, 자신에게 바인딩 된 이벤트 핸들러만 실행되고 끝남.

  <body>
    <div id="wrapper">
      <button>1</button>
      <button>2</button>
      <button id="three">3</button>
      <button>4</button>
      <button>5</button>
    </div>
    <script>
      const wrapper = document.querySelector('#wrapper');
      wrapper.addEventListener('click', () => console.log('clicked!'));

      const threeEl = document.querySelector('#three');
      threeEl.addEventListener('click', (e) => {
        console.log('three!');
        e.stopPropagation();
      });
    </script>
   </body>

→ 실행 결과

  • 3번 버튼 클릭 : three! (clicked! 실행 안됨)
  • 1번 버튼 클릭 : clicked!

🔶 Dom요소의 기본 동작 중단

Event.preventDefault()

: Dom요소의 기본 동작을 중단시킴

  <body>
    <a href="http://www.google.com">google home</a>
    <input type="checkBox" />
    
    <script>
      const aEl = document.querySelector('a');
      // 1. a태그의 링크 이동하는 속성을 중단시킴
      aEl.addEventListener('click', (e) => {
        e.preventDefault();
        alert('a tag clicked');
      });
      
	  // 2. checkBox기능을 중단시킴. 
      const checkBoxEl = document.querySelector('input');
      checkBoxEl.addEventListener('click', (e) => {
        e.preventDefault();
        alert('checkBox clicked');
      });
    </script>
   </body>

0개의 댓글