I have the following object:
mind = {
queries: [],
actions: []
};
and I update queries and actions according to another function.
I wanted to detect every time they're being updated and changed, and i've heard about MutationObserver, so I tried to call it:
var muob = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver);
var ob = new muob(function(m) {
console.log('It works!');
});
ob.observe(mind, { subtree: true });
But it doesn't work. I get in return:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
What's wrong with my code?
MutationObserver is only something that works for DOM elements, not objects:
For what you're doing, you can make the
queriesandactionsproperties have methods to update the arrays instead, eg:Or, using a Proxy:
(the above snippet logs
Change detectedtwice because it has to update both the0property on the array and change the array's.length)Still, this is pretty odd - it would be much more elegant if, at the location in the code where you change the array, you also call another function (the
It works!part) to indicate an update has occurred.