12.14.06
Using watch to monitor Javascript
I don’t know why, but no one seems to use Javascript’s watch(). It’s such a useful function, since it can change other variables when one changes. Here’s some example code.
var ref_count = 2;
watch(”ref_count”, handle_ref);
function handle_ref(id, old_val, new_val) {
if(new_val < 0) {
document.writeln("stopping decrement for "+ id);
return 0;} else {
return new_val;}
}
document.writeln("ref now "+ref_count+" ");
ref_count--;
document.writeln("ref now "+ref_count+" ");
ref_count--;
document.writeln("ref now "+ref_count+" ");
ref_count--;document.writeln("ref is now "+ref_count+" ");
In this case, ref_count never falls below zero. Here’s another.
location.watch(”href”,handle_href);
function handle_href(id, old_val, new_val) {
alert(”next location: “+new_val);
return new_val;}
setTimeout(”location.href = ‘http://search.yahoo.com/’”, 3000);location.watch(”href”,handle_href);
function handle_href(id, old_val, new_val) {
alert(”next location: “+new_val);
return new_val;}
setTimeout(”location.href = ‘http://search.yahoo.com/’”, 3000);
This one waits 3 seconds, warns you about the change of location, and loads the next page. This is interesting in that the ‘location’ object watches for one of its variables, ‘href’. Using watch(), a coder can change more than one AJAX innerHTML element at once or keep separate variables in sync with each other.
The Woodwork » Blog Archive » Javascript monitoring said,
December 17, 2006 at 5:21 am
[…] To not be a completely friend-serving post, I’ll mention that Dave has a short entry on Javascript watch(). A few months back I wanted to write a short blog entry on this little-known, highly-useful feature, but linking this blog entry saves me the trouble (and ups his vanity rating). […]
Roddy Heijst de Zeilen said,
October 8, 2008 at 8:24 am
About noone using .watch().. While the function is incredibly viable, the whole culture of JavaScript & all other browser-sided scripts seems to be held back by the fact that most of the companies/corporations use outdated browsers: for them, it is easier not to update all their computers. Simply said, I’m programming for IE6 right now, even though it has been released ‘way back’ in 2001. Apparently, 7 years is not that much to a large corporation.
IE6 is roughly 80% of the market share at those corporations, and it doesn’t support the .watch() function. That’s why I cannot use it, and I bet a lot of others with me.. It’s a shame really. We should stand up and fight, make them download Firefox or something ;] but alas, there is no power.
I’ll be keeping an eye on http://www.w3counter.com/globalstats.php anyway.. when IE6 hits 10%, i’m gonna drop it ;}