[javascript] 이 간단한 addEventListener 함수 뒤에 ‘false’가 사용되는 이유는 무엇입니까?

끝에 대한 거짓은 무엇입니까? 감사.

window.addEventListener('load', function() {
  alert("All done");
}, false);



답변

MDN Web Docs 에 따르면 세 번째 매개 변수는 다음과 같습니다.

useCapture를
하는 경우는 true, useCapture사용자가 캡처를 시작하고자하는 것을 나타냅니다. 캡처를 시작한 후 지정된 유형의 모든 이벤트 는 DOM 트리에서 그 아래 에있는 모든 이벤트로 전달 listener되기 전에 등록 된 이벤트 로 전달됩니다 EventTarget. 트리를 통해 위로 버블 링되는 이벤트는 캡처를 사용하도록 지정된 리스너를 트리거하지 않습니다.
자세한 설명 은 DOM 레벨 3 이벤트 를 참조하십시오 .


답변

나도 MDN을 확인했지만 여전히 그것이 무엇인지 이해하지 못했기 useCapture때문에이 답변은 공식 문서를 확인한 후에도 여전히 얻지 못하는 사람들을위한 것입니다.

따라서 우선 거의 모든 브라우저에서 다음이 발생합니다.

IE <9를 제외한 모든 브라우저에는 두 단계의 이벤트 처리가 있습니다.

이벤트는 먼저 중단 됩니다 . 이를 캡처 링 이라고 한 다음 거품이 발생합니다 . 이 동작은 W3C 사양에서 표준화되었습니다.

useCapture, 무엇을 설정하든 이 두 가지 이벤트 단계는 항상 존재합니다.

이 그림은 작동 방식을 보여줍니다.

여기에 이미지 설명 입력

이 모델에 따르면 이벤트 :

아래로 캡처-1-> 2-> 3.

거품 위로-3-> 2-> 1.

그러면 질문이 온다. 호출 된 세 번째 매개 변수는 useCapture핸들러가 이벤트를 처리하기를 원하는 두 단계를 나타냅니다.

useCapture = true

처리기는 캡처 단계에서 설정됩니다. 이벤트는 아이들에게 도착하기 전에 도착합니다.

useCapture = false.

핸들러는 버블 링 단계에서 설정됩니다. 이벤트는 아이들에게 도착한 후에 얻을 것입니다.

즉, 다음과 같은 코드를 작성하면 다음과 같습니다.

child.addEventListener("click", second);
parent.addEventListener("click", first, true);

자식 요소를 클릭 할 때, first방법은 전에 호출됩니다 second.

기본적으로 useCapture플래그는 false 로 설정되어 이벤트 버블 링 단계 에서만 핸들러가 호출됩니다 .

자세한 정보를 보려면이 참조 링크이를 클릭하십시오 .


답변

@Libra의 대답은 매우 좋습니다. 저와 같은 코드와 기계의 상호 작용을 더 잘 이해하는 사람들이 있습니다.
따라서 다음 스크립트는 이벤트 전파를 설명해야합니다. 내가이 기준으로 할 노력하고있어 설명 스키마 것은 입니다 :
다음 이벤트가 아래로 흘러 다음과 같은 계층 구조까지 :

<window>
<document>
<body>
<section>
<div>
<paragraph>
<span>

단순함을 위해 본문에서 캡처 단계에 대한 핸들러를 등록하는 span 요소로 시작하고 버블 링 단계에 대한 핸들러를 등록하는 body 요소로 백업합니다. 따라서 결과는 시작부터 끝까지 이벤트가 취하는 방향을 노드별로 나타냅니다. 로그에 액세스하려면 스 니펫의 오른쪽 패널에서 “콘솔 표시”를 클릭하십시오.

    function handler(e){
        /* logs messages of each phase of the event flow associated with 
        the actual node where the flow was passing by */

        if ( e.eventPhase == Event.CAPTURING_PHASE ){
            console.log ("capturing phase :\n actual node : "+this.nodeName);
        }
        if ( e.eventPhase == Event.AT_TARGET){
            console.log( "at target phase :\n actual node : "+this.nodeName);
        }
        if ( e.eventPhase == Event.BUBBLING_PHASE){
            console.log ("bubbling phase :\n actual node : "+this.nodeName );
        }
    }

    /* The following array contains the elements between the target (span and you can
    click also on the paragraph) and its ancestors up to the BODY element, it can still
    go up to the "document" then the "window" element, for the sake of simplicity it is 
    chosen to stop here at the body element
    */

    arr=[document.body,document.getElementById("sectionID"),
    document.getElementById("DivId"),document.getElementById("PId"),
        document.getElementById("spanId")];

    /* Then trying to register handelers for both capturing and bubbling phases
    */
        function listener(node){
            node.addEventListener( ev, handler, bool )
            /* ev :event (click), handler : logging the event associated with 
            the target, bool: capturing/bubbling phase */
        }
        ev="click";
        bool=true; // Capturing phase
        arr.forEach(listener);
        bool=false; // Bubbling phase
        /* Notice that both capturing and bubbling 
        include the at_target phase, that's why you'll get two `at_target` phases in
        the log */
        arr.forEach(listener);
        p {
            background: gray;
            color:white;
            padding: 10px;
            margin: 5px;
            border: thin solid black
        }
        span {
            background: white;
            color: black;
            padding: 2px;
            cursor: default;
        }
    <section ID="sectionID">
            <div  id="DivId">
                <p id="PId">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis <span id="spanId">CLICK ME </span> imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.
                </p>
            </div>
    </section>

초점과 같은 이벤트는 버블 링되지 않으므로 여전히 대부분의 이벤트가 버블 링됩니다.


답변