3
돌연변이 옵저버와 콜백 함수의 연결을 끊을 수 있습니까? 변경 사항은 꼭 준수해야하지만 처음 변경 한 후에는 관찰자의 연결을 끊고 싶습니다. 옵저버 변수가 범위를 벗어 났으므로 옵저버 변수는 분리되어 있지 않습니다. 코드가 작동하도록 observer 변수를 콜백 함수에 전달하려면 어떻게해야합니까?돌연변이 옵저버와 콜백 함수의 연결 해제
function mutate(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'characterData') {
console.log('1st change.');
observer.disconnect(); // Should disconnect here but observer variable is not defined.
}
else if (mutation.type === 'childList') {
console.log('2nd change. This should not trigger after being disconnected.');
}
});
}
jQuery(document).ready(function() {
setTimeout(function() {
document.querySelector('div#mainContainer p').innerHTML = 'Some other text.';
}, 2000);
setTimeout(function() {
jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>');
}, 4000);
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>
<body>
<div id="mainContainer">
<h1>Heading</h1>
<p>Paragraph.</p>
</div>
</body>
예, 그렇다면 observer 변수를 mutate()의 인수로 어떻게 전달합니까? 코드를 작성하여 테스트 할 수 있습니까? 코드가 어떻게 작동하는지보고 싶습니다. –
'MutationObserver'는'mutations'와 같은 방식으로 자동으로 전달할 필요가 없습니다. – loganfsmyth
JS가 어떻게이 작업을 수행 할 수 있습니까? 나는 자동적으로 인자를 전달하는 프로그래밍 언어를 결코 알지 못했다. 이 특수 기능은 JS에 이름이 있습니까? –