I have to execute two functions in jQuery when a mutation is triggered after clicking a button:
function mutate(mutations) {
mutations.forEach(function(mutation) {
function1().done(
function2()
);
});
}
var target = document.querySelector('#identifier')
var observer = new MutationObserver( mutate );
var config = { characterData: false, attributes: false, childList: true, subtree: false };
observer.observe(target, config);
The code is working properly, but I was expecting that the mutation was fired only one time when I click a specified button; but for some reason the mutation happens twice, and then the code is executed twice too. I can't modify the code that triggers the mutation, so I can modify only the mutation handling (the code above).
Is there any way to prevent the twice execution each time? I should use a different method intead of forEach, but which one?
Thanks in advance
I founded a solution: when I click the button a node is removed and suddenly recreated. That's why I get two mutations.
I've added an if
to make sure that the call is made only when the node is recreated
function mutate(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes.length > 0 && mutation.removedNodes.length == 0) {
function1().done(
function2()
);
}
});
}