【问题标题】:MutationObserver LimitMutationObserver 限制
【发布时间】: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


【解决方案1】:

您可以在闭包范围内捕获计数器,例如

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,这应该会很好。

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2017-12-10
    • 2023-03-25
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2018-07-26
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多