MutationObserver限制

时间:2016-12-26 19:37:33

标签: javascript callback handler mutation-observers

如何为突变观察者实现一个计数器,以限制它在断开连接之前监视的更改数量?在我所包含的小提琴中,我们的想法是,一旦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>

1 个答案:

答案 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,这应该会很有效。