Reputation: 486
For example, I want to write some codes in .my-codes
.
<head>
<script class="my-codes">
var ob = new MutationObserver(
function (mutations) {
mutations.forEach(
mutation => {
mutation.addedNodes.forEach(
node => {
if(node.nodeName === "DIV"){
// Without this browser may crush for infinite recursion
this.disconnect();
let innerNode = document.createElement("div");
innerNode.className = "inner-div";
console.log("Insert div to a ." + node.className);
node.appendChild(innerNode);
// Method below does not exist
/* this.reconnect(); */
}
}
)
}
);
}
);
ob.observe(document, {childList:true, subtree:true});
</script>
</head>
<body>
<div class="div1">
<script>
let asyncDiv = document.createElement("div");
asyncDiv.className = "div3";
setTimeout(()=>document.body.appendChild(asyncDiv), 10);
</script>
</div>
<div class="div2"></div>
</body>
Expected Result (if something like this.reconnect();
exists) :
<div class="div1">
<div class="inner-div"></div>
</div>
<div class="div2">
<div class="inner-div"></div>
</div>
<div class="div3">
<div class="inner-div"></div>
</div>
Actual Result (the observation completely stopped after the first insertion):
<div class="div1">
<div class="inner-div"></div>
</div>
<div class="div2"></div>
<div class="div3"></div>
Is there a reliable way to implement the this.reconnect();
function?
(It will be better not to mess with global variables, codes below is not considered a reliable way since the callback function need to capture global variable)
var target = document;
var config = {childList:true, subtree:true};
var ob = new MutationObserver(
function(mut, observer){
this.disconnect();
/* mess with DOM */
observer.observe(target, config);
}
)
ob.observe(target, config);
Upvotes: 7
Views: 3159
Reputation: 138257
It seems the right way to use kind of global variables . But they dont need to be global:
function observe(target,config){
target =target|| document;
config = config||{childList:true, subtree:true};
var ob = new MutationObserver(function(mut, observer){
ob.disconnect();
/* mess with DOM */
ob.observe(target, config);
});
ob.observe(target, config);
}
observe();
This can be extended to provide a more general way of observing:
function customObserver(target,config,callback){
this.target =target|| document;
this.config = config||{childList:true, subtree:true};
var that=this;
this.ob = new MutationObserver(function(mut,observer){
callback.call(that,mut,observer);
});
}
customObserver.prototype={
connect:function(){
this.ob.observe(this.target,this.config);
},
disconnect:function(){ this.ob.disconnect()}
};
So one can do:
var observer=new customObserver(document,false,function(observer,mutations){
observer.disconnect();
//som DOM changes
observer.connect();
});
observer.connect();
Upvotes: 3