2016-12-25 8 views
3

돌연변이 옵저버와 콜백 함수의 연결을 끊을 수 있습니까? 변경 사항은 꼭 준수해야하지만 처음 변경 한 후에는 관찰자의 연결을 끊고 싶습니다. 옵저버 변수가 범위를 벗어 났으므로 옵저버 변수는 분리되어 있지 않습니다. 코드가 작동하도록 observer 변수를 콜백 함수에 전달하려면 어떻게해야합니까?돌연변이 옵저버와 콜백 함수의 연결 해제

function mutate(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    if (mutation.type === 'characterData') { 
 
     console.log('1st change.'); 
 
     observer.disconnect(); // Should disconnect here but observer variable is not defined. 
 
    } 
 
    else if (mutation.type === 'childList') { 
 
     console.log('2nd change. This should not trigger after being disconnected.'); 
 
    } 
 
    }); 
 
} 
 

 
jQuery(document).ready(function() { 
 
    setTimeout(function() { 
 
    document.querySelector('div#mainContainer p').innerHTML = 'Some other text.'; 
 
    }, 2000); 
 

 
    setTimeout(function() { 
 
    jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>'); 
 
    }, 4000); 
 

 
    var targetOne = document.querySelector('div#mainContainer'); 
 
    var observer = new MutationObserver(mutate); 
 
    var config = { attributes: true, characterData: true, childList: true, subtree: true }; 
 

 
    observer.observe(targetOne, config); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <div id="mainContainer"> 
 
    <h1>Heading</h1> 
 
    <p>Paragraph.</p> 
 
    </div> 
 
</body>

답변

4

돌연변이와 관련된 관찰자 인스턴스가 자동으로 전달되기 때문에 가장 쉬운 방법은 콜백

function mutate(mutations) { 

function mutate(mutations, observer) { 

을 조정하는 것 t에 대한 두 번째 매개 변수 he mutation handler 함수.

그러면 언제든지 observer.disconnect()으로 전화 할 수 있습니다.

+0

예, 그렇다면 observer 변수를 mutate()의 인수로 어떻게 전달합니까? 코드를 작성하여 테스트 할 수 있습니까? 코드가 어떻게 작동하는지보고 싶습니다. –

+1

'MutationObserver'는'mutations'와 같은 방식으로 자동으로 전달할 필요가 없습니다. – loganfsmyth

+0

JS가 어떻게이 작업을 수행 할 수 있습니까? 나는 자동적으로 인자를 전달하는 프로그래밍 언어를 결코 알지 못했다. 이 특수 기능은 JS에 이름이 있습니까? –