12.14.06

Using watch to monitor Javascript

Posted in Coding at 11:32 am by David Kellogg

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.

1 Comment »

  1. 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). […]

Leave a Comment