Object.prototype.watch()

  • Revision slug: JavaScript/Reference/Global_Objects/Object/watch
  • Revision title: watch
  • Revision id: 49866
  • Created:
  • Creator: dbruant
  • Is current revision? No
  • Comment Mostly formatting; 5 words added, 3 words removed

Revision Content

{{ Non-standard_header() }}

Summary

Watches for a property to be assigned a value and runs a function when that occurs.

Method of Object
Implemented in JavaScript 1.2
ECMAScript Edition none

Syntax

object.watch(prop, handler)

Parameters

prop
The name of a property of the object.
handler
A function to call.

Description

Watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval).

If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect.

To remove a watchpoint, use the unwatch method. By default, the watch method is inherited by every object descended from Object.

The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman.

In NES 3.0 and 4.x, handler is called from native code as well as assignments in script. In Firefox, handler is only called from assignments in script, not from native code. For example, window.watch('location', myHandler) will not call myHandler if the user clicks a link to an anchor within the current document. However, window.location += '#myAnchor' will call myHandler:

Examples

Example: Using watch and unwatch

var o = {p:1};
o.watch("p",
  function (id, oldval, newval) {
    console.log("o." + id + " changed from " + oldval + " to " + newval);
    return newval;
  });

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

o.unwatch('p');
o.p = 5;

This script displays the following:

o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from undefined to 4

Example: Using watch to validate an object's properties

You can use watch to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200.

Person = function(name,age) {
  this.watch("age", Person.prototype._isValidAssignment);
  this.watch("name", Person.prototype._isValidAssignment);
  this.name = name;
  this.age = age;
}

Person.prototype.toString = function() {
  return this.name + ", " + this.age;
};

Person.prototype._isValidAssignment = function(id, oldval, newval) {
  if (id === "name" && (!newval || newval.length > 30)) {
    throw new RangeError("invalid name for " + this);
  }
  if (id === "age"  && (newval < 0 || newval > 200)) {
    throw new RangeError("invalid age for " + this);
  }
  return newval;
}

will = new Person("Will", 29);
print(will);   // Will, 29

try {
  will.name = "";
} catch (e) {
  print(e);
}

try {
  will.age = -4;
} catch (e) {
  print(e);
}

This script displays the following:

Will, 29
RangeError: invalid name for Will, 29
RangeError: invalid age for Will, 29

Compatibility

This polyfill by Eli Grey offers Object.prototype.watch too all browsers with ES5 or the legacy __defineGetter__ functionality.

See Also

unwatch

{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/Object/watch", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Object/watch", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Object/watch" } ) }}

Revision Source

<p>{{ Non-standard_header() }}</p>
<h2 name="Summary">Summary</h2>
<p>Watches for a property to be assigned a value and runs a function when that occurs.</p>
<table class="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>JavaScript 1.2</td> </tr> <tr> <td>ECMAScript Edition</td> <td>none</td> </tr> </tbody>
</table>
<h2 name="Syntax">Syntax</h2>
<p><code><em>object</em>.watch(<em>prop</em>, <em>handler</em>) </code></p>
<h2 name="Parameters">Parameters</h2>
<dl> <dt><code>prop</code></dt> <dd>The name of a property of the object.</dd>
</dl>
<dl> <dt><code>handler</code></dt> <dd>A function to call.</dd>
</dl>
<h2 name="Description">Description</h2>
<p>Watches for assignment to a property named <code>prop</code> in this object, calling <code>handler(prop, oldval, newval)</code> whenever <code>prop</code> is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified <code>newval</code> (or by returning <code>oldval</code>).</p>
<p>If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect.</p>
<p>To remove a watchpoint, use the <code><a href="/en/JavaScript/Reference/Global_Objects/Object/unwatch" title="en/JavaScript/Reference/Global_Objects/Object/unwatch">unwatch</a></code> method. By default, the <code>watch</code> method is inherited by every object descended from <code>Object</code>.</p>
<p>The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see <a href="/en/Venkman" title="en/Venkman">Venkman</a>.</p>
<p>In NES 3.0 and 4.x, <code>handler</code> is called from native code as well as assignments in script. In Firefox, <code>handler</code> is only called from assignments in script, not from native code. For example, <code>window.watch('location', myHandler)</code> will not call <code>myHandler</code> if the user clicks a link to an anchor within the current document. However, <code>window.location += '#myAnchor'</code> will call <code>myHandler</code>:</p>
<h2 name="Examples">Examples</h2>
<h3 name="Example:_Using_watch_and_unwatch">Example: Using <code>watch</code> and <code>unwatch</code></h3>
<pre class="brush: js">var o = {p:1};
o.watch("p",
  function (id, oldval, newval) {
    console.log("o." + id + " changed from " + oldval + " to " + newval);
    return newval;
  });

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

o.unwatch('p');
o.p = 5;
</pre>
<p>This script displays the following:</p>
<pre class="eval">o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from undefined to 4
</pre>
<h3 name="Example:_Using_watch_to_validate_an_object.27s_properties">Example: Using <code>watch</code> to validate an object's properties</h3>
<p>You can use <code>watch</code> to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200.</p>
<pre class="brush: js">Person = function(name,age) {
  this.watch("age", Person.prototype._isValidAssignment);
  this.watch("name", Person.prototype._isValidAssignment);
  this.name = name;
  this.age = age;
}

Person.prototype.toString = function() {
  return this.name + ", " + this.age;
};

Person.prototype._isValidAssignment = function(id, oldval, newval) {
  if (id === "name" &amp;&amp; (!newval || newval.length &gt; 30)) {
    throw new RangeError("invalid name for " + this);
  }
  if (id === "age"  &amp;&amp; (newval &lt; 0 || newval &gt; 200)) {
    throw new RangeError("invalid age for " + this);
  }
  return newval;
}

will = new Person("Will", 29);
print(will);   // Will, 29

try {
  will.name = "";
} catch (e) {
  print(e);
}

try {
  will.age = -4;
} catch (e) {
  print(e);
}
</pre>
<p>This script displays the following:</p>
<pre class="eval">Will, 29
RangeError: invalid name for Will, 29
RangeError: invalid age for Will, 29
</pre>
<h2>Compatibility</h2>
<p><a class="link-https" href="https://gist.github.com/175649">This polyfill by Eli Grey</a> offers Object.prototype.watch too all browsers with ES5 or the legacy<a href="/en/JavaScript/Reference/Global_Objects/Object/defineGetter" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineGetter"> __defineGetter__</a> functionality.</p>
<h2 name="See_Also">See Also</h2>
<p><a href="/en/JavaScript/Reference/Global_Objects/Object/unwatch" title="en/JavaScript/Reference/Global_Objects/Object/unwatch">unwatch</a></p>
<p>{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/Object/watch", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Object/watch", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Object/watch" } ) }}</p>
Revert to this revision