watch() (Function/global)

Set a watch-point for a named property of an object.

Availability:

JavaScript - 1.2
Netscape - 4.0
JavaScript syntax:NmyObject.watch(aProperty, aHandler)
Argument list:aHandlerA handler that gets called when the property changes
aPropertyA property to watch

This method is provided to ease the task of debugging JavaScript.

It provides a general purpose way to call an unconnected function when a property value is changed. The function does not need to be called explicitly. The function that gets called has a particular API, which passes the following values:

It gets an opportunity to modify the new value or veto the change by returning the old value. Whatever value is returned is stored in the property. You can carry out other JavaScript tasks during this property call, although it is probably to best avoid making changes to other property values with watch-points that call the same handler, because you could set up a recursive loop.

If you invoke the watch() method without specifying a receiving object, as if it were a function, you are actually setting watch-points on global object properties. Since this is where global variables live, you can monitor them as easily as object properties.

The new event model supported by Netscape 6.0 and that already available in MSIE 5.0 present a propertyName property that belongs to the Event object. You can inspect that during an onPropertyChanged event and achieve the same watch()/unwatch() behavior.

Example code:

   <HTML>

   <HEAD>

   </HEAD>

   <BODY>

   <SCRIPT>

   // Code works with Netscape 4+ only

   // Define initial value for property

   var XXX = 10;

   // Define watch handler function

   function watchHandler(aProp, anOldVal, aNewVal)

   {

      var myText = "";

   

      myText += "Property name ...: ";

      myText += aProp;

      myText += "\n";

   

      myText += "Old value .......: ";

      myText += anOldVal;

      myText += "\n";

   

      myText += "New value .......: ";

      myText += aNewVal;

      myText += "\n";

   

      alert(myText);

      return aNewVal;

   }

   // Register the watch handler

   watch("XXX", watchHandler);

   </SCRIPT>

   Some body text

   <SCRIPT>

   // Modify the property to trigger the watch handler

   XXX = 1000;

   </SCRIPT>

   </BODY>

   </HTML>

See also:Event, Event handler, Event management, Event model, Event object, onPropertyChange, unwatch(), Watchpoint handler

Cross-references:

Wrox Instant JavaScript - page - 56