2016-12-25 38 views
3

如何将我的突变观察者从其回调函数断开?正在观察这些变化,因为他们应该这样做,但我想在第一次变更后断开观察者。由于观察者变量超出了范围,因此它不会像应该那样断开连接。我如何将观察者变量传递给回调函数,以便代码可以工作?从回调函数断开突变观察者

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>

回答

4

最简单的方法是调整你的回调

function mutate(mutations) { 

function mutate(mutations, observer) { 

因为与突变相关的观测实例作为自动传递第二个参数为t他突变处理函数。

然后您可以在任何需要的时候致电observer.disconnect()

+0

是的,但那么你会如何将观察变量作为参数传递给mutate()?你能详细说明你的代码,所以我不能测试它吗?我很想看看你的代码如何工作。 –

+1

你不需要,'MutationObserver'自动地传递它,就像它传递'mutation'一样。 – loganfsmyth

+0

JS是如何做到这一点的?我从来不知道一种编程语言会自动为你传递参数。这个特殊功能在JS中有一个名字吗? –