faqts : Computers : Programming : Languages : JavaScript : Language Core : Variables

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 4 people (75%) answered Yes
Recently 3 of 4 people (75%) answered Yes

Entry

How can I detect when a variable change value

Aug 24th, 2001 16:05
Juergen Thelen, Dario Copia,


Hi Dario,
With NN4 and NN6 you can use the watch() and unwatch() methods, that 
are inherited by every object (that was descended from an Object).
Here's a sample showing this technique:
--- snip ---
<HTML>
<HEAD>
<TITLE>Untitled Document</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<SCRIPT language="JavaScript1.2">
<!--
var myGlobal = "hello";
window.watch("myGlobal", function (id, oldValue, newValue)
{
  document.writeln("window." + id + " was " + oldValue +", now: " + 
newValue + '<BR>');
  return newValue;
});
myGlobal = "world";
myObject = new Object();
myObject.myProperty = 4711;
myObject.watch("myProperty", function (id, oldValue, newValue)
{
  document.writeln("myObject." + id + " was " + oldValue +", now: " + 
newValue);
  return newValue;
});
myObject.myProperty = 9876;
//-->
</SCRIPT>
</HEAD>
<BODY bgcolor="#FFFFFF" text="#000000">
</BODY>
</HTML>
--- snap ---
IE and most other browsers unfortunately do not implement the watch() 
and unwatch() methods, so I usually simply write the values of the 
variables I am interested in into either an alert box (using alert()), 
or into the windows statusbar (using window.status = variable).
For IE5 you can also use the onpropertychange event, which is similiar 
to watch(), but afaik this works only for its DOM properties. Never 
tested it...
Hth, Juergen