2016-12-26 53 views
0

如何實現突變觀察者的計數器,以限制它在斷開之前監視的更改次數?在我包括的小提琴中,想法是一旦var數大於1,觀察者應該斷開連接。但是因爲變量每次調用觀察者處理程序都會重置,所以它不起作用。我怎樣才能實現我想要做的事情?MutationObserver限制

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功能而不全球。

只要你不需要訪問mutate以外的count這應該很好。