2017-07-19 5 views
0

いくつかのDOMノード属性を同期したいと思います。属性が変更されると、他の要素の属性が変更されます。MutationObserverをテストするには

私はそれを変更できますが、私はそれのためのテストを書くことはできません。このテストでは、観測された要素の属性が変更され、変更が他の要素に適用されているかどうかが確認されます。変更の同期は最終的には発生しますが、観測された要素の属性が変更された直後には発生しません。

this example私は3つのdivを作成し、クラス属性を#div1と他の2つに同期させたいとします。

HTML:

<div id="div1" class="foo"></div> 
<div id="div2" class="foo"></div> 
<div id="div3" class="foo"></div> 

JS:

let div1 = document.getElementById("div1") 
let div2 = document.getElementById("div2") 
let div3 = document.getElementById("div3") 

var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    console.log(mutation.target.getAttribute("class")) 
    //sync the new attribute value to 
    div2.setAttribute("class", mutation.target.getAttribute("class")) 
    div3.setAttribute("class", mutation.target.getAttribute("class")) 
    }) 
}) 
// pass in the target node, as well as the observer options 
observer.observe(div1, { attributes: true, attributeFilter: ["class"]}) 

//the test sets the class attribute of div1 to 'bar' 
div1.setAttribute("class", "bar") 
//then checks if div2 and div3 class is set to 'bar' 
console.log("is div2.class = 'bar'?", div2.getAttribute("class") == "bar") 
console.log("is div3.class = 'bar'?", div3.getAttribute("class") == "bar") 

出力である:

is div2.class = 'bar'? false 
is div3.class = 'bar'? false 
bar 

MutationObserverのみをチェックした後に実行され、その後div2.classdiv3.classとは'bar'に設定されています。だから私の質問は、MutationObserverと属性の同期をテストする方法です。

答えて

2

更新されたクラスをチェックする前に突然変異イベントを処理するのを待つ必要があります。

よくあるおもちゃはsetTimeoutです。どのように動作するかについては、this questionを参照してください。

let div1 = document.getElementById("div1"); 
 
let div2 = document.getElementById("div2"); 
 
let div3 = document.getElementById("div3"); 
 

 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    console.log(mutation.target.getAttribute("class")); 
 
    div2.setAttribute("class", mutation.target.getAttribute("class")); 
 
    div3.setAttribute("class", mutation.target.getAttribute("class")); 
 
    }); 
 
}); 
 
// pass in the target node, as well as the observer options 
 
observer.observe(div1, { 
 
    attributes: true, 
 
    attributeFilter: ["class"] 
 
}); 
 

 
function testMutationObserver(mutation, afterMutation) { 
 
    //Perform the mutation, e.g. by setting a new class 
 
    mutation(); 
 
    
 
    //setTimeout gives the MutationObserver a chance to see the changes 
 
    setTimeout(afterMutation); 
 
} 
 

 
testMutationObserver(
 
    function() { 
 
    div1.setAttribute("class", "bar"); 
 
    }, 
 
    function() { 
 
    console.log("is div2.class = 'bar'?", div2.getAttribute("class") == "bar"); 
 
    console.log("is div3.class = 'bar'?", div3.getAttribute("class") == "bar"); 
 
    } 
 
);
<div id="div1" class="foo"></div> 
 
<div id="div2" class="foo"></div> 
 
<div id="div3" class="foo"></div>

関連する問題