【发布时间】:2016-12-26 19:37:33
【问题描述】:
如何对突变观察者实施计数器,以限制它在断开连接之前观察到的更改数量?在我包含的小提琴中,想法是一旦 var count 大于 1,观察者应该断开连接。但是由于每次调用观察者处理程序时变量都会重置,所以它不起作用。如何实现我正在尝试做的事情?
function mutate( mutations, observer ) {
var count = 0;
console.log('\nThe following mutation(s) occurred:');
mutations.every(function(mutation) {
if ( mutation.type === 'attributes' ) {
console.log('Attribute change.');
}
else if ( mutation.type === 'characterData' ) {
console.log('Text change.');
}
else if ( mutation.type === 'childList' ) {
if ( count > 1 ) {
observer.disconnect();
console.log('Disconnected.');
return false;
}
console.log('Element change.');
}
count++;
console.log('Count: ' + count);
});
}
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
document.getElementById('photo').src = 'http://i.imgur.com/Xw6htaT.jpg';
document.getElementById('photo').alt = 'Dog';
}, 2000);
setTimeout(function() {
document.querySelector('div#mainContainer p').innerHTML = 'Some other text.';
}, 4000);
setTimeout(function() {
jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>');
}, 6000);
setTimeout(function() {
jQuery('div.insertedDiv').remove();
}, 8000);
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>
<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>
【问题讨论】:
-
在函数外声明变量,不要重置
-
不使用全局变量,如何将变量传递给观察者的回调函数?
标签: javascript callback handler mutation-observers