2017-06-24 32 views
1

如何讓觀察實例MutationObserver忽略一些由我的代碼導致的DOM更改? 例如(使用jQuery):MutationObserver:忽略DOM動作

//initialize MutationObserver 
var mo = new MutationObserver(mutations => console.log(mutations)); 
mo.observe(document.body, {attributes: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true, childList: true}); 

//case 1: perform a removal 
$('.someDiv').remove(); 
//in this case an action is logged by MO 

//case 2: perform a removal with a disconnected MO 
mo.disconnect(); 
$('.someDiv').remove(); 
mo.observe(document.body, {...}); 
//in this case an action is logged again! 

在這兩種情況下,MO記錄我所做的DOM的所有更改。還有就是我想出的唯一辦法:

//case 3: perform a removal with a disconnected MO, turning on after a timeout 
mo.disconnect(); 
$('.someDiv').remove(); 
setTimeout(() => mo.observe(document.body, {...}), 500); //pseudo 
//in this case MO skips an action above 

但它不是這個問題的最佳解決方案,因爲可以有超時期間可由用戶造成頁面上一些其他動作,或MutationObserver的回調可能在超時之後的某個時間調用。

回答

2

MutationObserver的回調是異步調用的,因此當前執行的代碼所做的更改只有在完成時纔會累積並提交。
這就是JavaScript event loop的工作原理。

如果斷開,並在同一事件重新連接,你需要明確耗盡隊列:

mo.disconnect(); 
mo.takeRecords(); // deplete the queue 

.............. 

mo.observe(......);