Javascript Object.Watch for all browsers?

Posted by SeanW on Stack Overflow See other posts from Stack Overflow or by SeanW
Published on 2009-06-22T20:29:55Z Indexed on 2010/04/30 1:47 UTC
Read the original article Hit count: 286

Hey all, I was looking for an easy way to monitor an object or variable for changes, and I found Object.Watch that's supported in Mozilla browsers, but not IE. So I started searching around to see if anyone had written some sort of equivalent.

About the only thing I've found has been a jQuery plugin (http://plugins.jquery.com/files/jquery-watch.js.txt), but I'm not sure if that's the best way to go. I certainly use jQuery in most of my projects, so I'm not worried about the jQuery aspect...

Anyway, the question: can someone show me a working example of that jQuery plugin? I'm having problems making it work...

Or, does anyone know of any better alternatives that would work cross browser? Thanks!

Update after answers:

Thanks everyone for the responses! I tried out the code posted here: http://webreflection.blogspot.com/2009/01/internet-explorer-object-watch.html

But I couldn't seem to make it work with IE. The code below works fine in FireFox, but does nothing in IE. In Firefox, each time watcher.status is changed, the document.write in watcher.watch is called and you can see the output on the page. In IE, that doesn't happen, but I can see that watcher.status is updating the value, because the last document.write shows the correct value (in both IE and FF). But, if the callback function isn't called, then that's kind of pointless... :)

Am I missing something?

var options = {'status': 'no status'},
watcher = createWatcher(options);

watcher.watch("status", function(prop, oldValue, newValue) {
    document.write("old: " + oldValue + ", new: " + newValue + "<br>");
    return newValue;
});

watcher.status = 'asdf';
watcher.status = '1234';

document.write(watcher.status + "<br>");

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events