views:

657

answers:

2

Going through javascript documentation, I found the following two functions on a javascript object looks interesting:

Watch - Watches for a property to be assigned a value and runs a function when that occurs.
Unwatch - Removes a watchpoint set with the watch method.

Sample usage:

o = {p:1}; <br/>
o.watch("p",<br/>
   function (id,oldval,newval) {<br/>
      document.writeln("o." + id + " changed from " + oldval + " to " + newval)<br/>
      return newval;<br/>
   }) <br/>

Whenever we change the property value of "p",this function gets triggered.

o.p = 2;   //print "o.p changed from 1 to 2"

I am working on javascript for the fast few years and never used these functions.
Can some one please throw some good use cases where these functions will come handy?

A: 

What watch is really designed for is validation of property values. For example you could validate that something is an integer:

obj.watch('count', function(id, oldval, newval) {
    var val = parseInt(newval, 10);
    if(isNaN(val)) return oldval;
    return val;
});

You could use it to validate string length:

obj.watch('name', function(id, oldval, newval) {
    return newval.substr(0, 20);
});

However, these are only available in the latest versions of the SpiderMonkey javascript engine. Great if you are using Jaxer or embedding the SpiderMonkey engine, but not really available in your browser yet (unless you are using FF3).

Prestaul
A: 

Check out Object.defineProperty
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/defineProperty
and
Object.prototype._defineGetter_ (or _defineSetter_ )
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters
to see where this functionality is heading.

Object.defineProperty should be available in all contemporary browsers real soon now.

Sean Hogan