I have a MutationObserver object that is initialized with its callback function inside a function and observes a node that has one of its children's text changed every two seconds in order to change the text of another node to always be similar to that of the other one with the callback function.
In that same function, I check if an attribute of an object is the same as the parameter of the function. If it is, the MutationObserver object is initialized and if it isn't, the MutationObserver object is disconnected inside a try catch.
But even if the MutationObserver object is seemingly disconnected successfully, it still does its callback function and changes the text of the same node even though it is disconnected.
I tried declaring the observer variable outside the function but it still doesn't work. Here is an example of how my code works in general:
var observer;
var objectList = [{
id: 1,
text: "ObjectA",
},
{
id: 2,
text: "ObjectB",
},
{
id: 3,
text: "ObjectC",
}
]
function changeText(id) {
var i, callback, config;
for (i = 0; i < objectList.length; i++) {
if (objectList[i].id === id) {
config = {
characterData: true
};
callback = function () {
document.getElementById("textNode").innerHTML = document.getElementById("otherTextNode").innerHTML;
};
observer = new MutationObserver(callback);
observer.observe(document.getElementById("otherTextNode"), config)
return;
}
}
document.getElementById("textNode").innerHTML = "";
try {
observer.disconnect();
} catch (e) {
document.getElementById("textNode").innerHTML = e.message;
}
}
So when the function changeText() is called once with one of the objects' id property as the parameter, the MutationObserver is initialized and begins observing but when the parameter does not match the ids, the MutationObserver should stop but in my case it keeps going and the message displayed is "observer is undefined" even AFTER it was defined as a MutationObserver and that it keeps observing.