简体   繁体   English

从回调函数中断开Mutation Observer

[英]Disconnect Mutation Observer from Callback Function

How can I disconnect my mutation observer from its callback function? 如何断开我的变异观察者与其回调函数的连接? The changes are being observed as they should, but I would like to disconnect the observer after the first change. 正如他们应该观察到的变化,但我想在第一次变化后断开观察者。 Since the observer variable is out of scope, it's not disconnecting as it should. 由于观察者变量超出范围,因此它不会断开连接。 How can I pass the observer variable to the callback function so the code will work? 如何将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> 

The easiest way would be to adjust your callback 最简单的方法是调整回调

function mutate(mutations) {

to

function mutate(mutations, observer) {

because the observer instance associated with the mutations is automatically passed as the second parameter to the mutation handler function. 因为与突变关联的观察者实例会自动作为第二个参数传递给突变处理函数。

Then you can call observer.disconnect() at whichever time you need it. 然后你可以在任何需要的时候调用observer.disconnect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM