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.class
div3.class
とは'bar'
に設定されています。だから私の質問は、MutationObserver
と属性の同期をテストする方法です。