it is possible, technically, but since all the current JS implementations that I know of are single-threaded, it will not be very elegant. The only thing I can think of is a brute force interval:
var checkObj = (function(watchObj) { var initialMap = {},allProps = [],prop; for (prop in watchObj) { if (watchObj.hasOwnProperty(prop)) {//make tracer object: basically clone it initialMap[prop] = watchObj[prop]; allProps.push(prop);//keep an array mapper } } return function() { var currentProps = []; for (prop in watchObj) { if (watchObj.hasOwnProperty(prop)) {//iterate the object again, compare if (watchObj[prop] !== initialMap[prop]) {//type andvalue check! console.log(initialMap[prop] + ' => ' watchObj[prop]); //diff found, deal with it whichever way you see fit } currentProps.push(prop); } } //we're not done yet! if (currentProps.length < allProps.length) { console.log('some prop was deleted'); //loop through arrays to find out which one } }; })(someObjectToTrack); var watchInterval = setInterval(checkObj,100);//check every .1 seconds?
This allows you to track the object to some extent, but then again, it is quite a bit of work to do this 10 / sec. Who knows, maybe the object changes several times between intervals.
All in all, I feel this is a less idealized approach ... it might be easier to compare the string constants of the JSON.stringify 'ed object, but that means there are no missing functions and (although I filtered them in this example) prototype properties.
I considered doing something like this at some point, but in the end I used only event handlers that changed the object in question to check for any changes.
Alternatively, you can also try creating a DOMElement and attaching an onchange listener to it ... unfortunately, functions / methods may be difficult to track, but at least it wonโt slow your script down as described above.
Elias van ootegem
source share