2016-12-26 4 views
0

뮤 테이션 옵저버의 카운터를 구현하여 연결 해제 전에 변경 횟수를 제한하려면 어떻게해야합니까? 필자가 포함시킨 바이올린에서, var count가 1보다 크면 관측자는 연결을 끊어야한다는 아이디어가 있습니다. 그러나 observer 핸들러가 호출 될 때마다 변수가 재설정되기 때문에 작동하지 않습니다. 내가하려는 것을 어떻게 구현할 수 있습니까?MutationObserver Limit

function mutate(mutations, observer) { 
 
\t var count = 0; 
 
\t console.log('\nThe following mutation(s) occurred:'); 
 

 
\t mutations.every(function(mutation) { 
 
\t \t if (mutation.type === 'attributes') { 
 
\t \t \t console.log('Attribute change.'); 
 
\t \t } 
 
\t \t else if (mutation.type === 'characterData') { 
 
\t \t \t console.log('Text change.'); 
 
\t \t } 
 
\t \t else if (mutation.type === 'childList') { 
 
\t \t \t if (count > 1) { 
 
\t \t \t \t observer.disconnect(); 
 
\t \t \t \t console.log('Disconnected.'); 
 
\t \t \t \t return false; 
 
\t \t \t } 
 

 
\t \t \t console.log('Element change.'); 
 
\t \t } 
 

 
\t \t count++; 
 
\t \t console.log('Count: ' + count); 
 

 
\t }); 
 
} 
 

 
document.addEventListener('DOMContentLoaded', function() { 
 
\t setTimeout(function() { 
 
\t \t document.getElementById('photo').src = 'http://i.imgur.com/Xw6htaT.jpg'; 
 
\t \t document.getElementById('photo').alt = 'Dog'; 
 
\t }, 2000); 
 

 
\t setTimeout(function() { 
 
\t \t document.querySelector('div#mainContainer p').innerHTML = 'Some other text.'; 
 
\t }, 4000); 
 

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

 
\t setTimeout(function() { 
 
\t \t jQuery('div.insertedDiv').remove(); 
 
\t }, 8000); 
 

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

 
\t observer.observe(targetOne, config); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="mainContainer"> 
 
    <h1>Heading</h1> 
 
    <p>Paragraph.</p> 
 
    <img src="http://i.stack.imgur.com/k7HT5.jpg" alt="Photo" id="photo" height="100"> 
 
</div>

+1

함수 외부에서 변수 선언 및 재설정 안 함 – charlietfl

+0

전역 변수를 사용하지 않으면 어떻게 변수를 옵저버의 콜백 함수에 전달할 수 있습니까? –

답변

0

당신은 폐쇄 범위에서, 예를 들어, 카운터를 캡처 할 수 있습니다

function mutate(mutations, observer) { 
    // ... 
} 

// ... 
var observer = new MutationObserver(mutate); 

function createMutateHandler() { 
    var count = 0; 

    return function mutate(mutations, observer) { 
    // ... 
    count++; 
    }; 
} 

// ... 
var observer = new MutationObserver(createMutateHandler()); 

에 따라서 가변 count 글로벌 인 않고 mutate 함수와 함께 존재한다.

count 외부에 mutate 외부에 액세스 할 필요가없는 한이 방법이 효과적입니다.