본문 바로가기
WEB/JavaScript

이벤트 : 전파

by 노랑파랑 2016. 10. 16.
반응형




이벤트 전파

* 부모 - 자식의 계층 구조로 이루어진 각각의 요소에 이벤트를 부여할 때 이벤트 순서를 정할 수 있다.



1. 캡처링 ( Capturing )

* 부모노드에서 자식노드로 이벤트가 전파된다.

* 낮은 IE 버전에서는 작동하지 않아 선호되는 방식은 아니다.

item.addEventListener("이벤트 타입", 이벤트 핸들러, true);

W3C events order




2. 버블링 ( Bubbling )

* 자식 노드부터 부모 노드로 이벤트가 전파된다.

item.addEventListener("이벤트 타입", 이벤트 핸들러, false);

Bubbling events order




3. 캡처링과 버블링 예제

<html> <body id="theBody" class="item"> <div id="one_a" class="item"> <div id="two" class="item"> <div id="three_a" class="item"> <button id="buttonOne" class="item">one</button> </div> <div id="three_b" class="item"> <button id="buttonTwo" class="item">two</button> <button id="buttonThree" class="item">three</button> </div> </div> </div> <div id="one_b" class="item"> </div> <script> var items = document.querySelectorAll(".item"); for (var i = 0; i < items.length; i++) { var el = items[i];                 //capturing phase  =     trune el.addEventListener("click", doSomething, true);                 //bubbling phase    =     false el.addEventListener("click", doSomething, false); } function doSomething(e) { alert(e.currentTarget.id); } </script> </body> </html>


위의 예제 코드를 계층화 해서 보면 아래와 같다

the DOM for this example



 캡처링 이벤트 전파일 때                                                                           버블링 전파일 때

the capture phase      bubbles bubbles bubbles        




4. 이벤트 전파 차단

* 다층 구조의 노드에 이벤트를 각각 부여했을 때 특정 위치에서 이벤트를 차단해야 하는 경우도 종종 있다.

* 아래 예제를 위 예제에 추가하면 three_a 노드에서 콜백함수에서 전달받은 stopPropagation() 메소드를 사용해

  three_a 이후의 이벤트 전파가 차단된다.

  var theElement = document.querySelector("#three_a");
      theElement.addEventListener("click", doSomething2, true);
 
      function doSomething2(e) {
          e.stopPropagation();
      }

the event is stopped


반응형

'WEB > JavaScript' 카테고리의 다른 글

이벤트 : Type  (0) 2016.10.17
이벤트 : 기본 이벤트 취소  (0) 2016.10.17
이벤트 : 등록방법  (0) 2016.10.16
이벤트  (0) 2016.10.16
요소의 위치와 크기  (0) 2016.10.16