views:

33

answers:

1

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Object/watch

The .watch() method does this in short: "Watches for a property to be assigned a value and runs a function when that occurs."

Long descriptive form: "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)."

There is a question for getting it to work in all browsers here: http://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers

I am looking for something similar to that. What I'm looking for is a method I can use to fit this specification: "Watches for assignment to any property in this object and runs a function when that occurs." The main difference is that it is any property, and just any specific property.

Can somebody create such a method or if they know such a method is already in existence, link to it? It'd be useful to have it work in all browsers (minus IE, or minus IE8 if IE9 conforms)

Edit: For an example of what I mean, I'll show what I need it for.

var DiscreteLine = function (leftBound, length){
  this.positive = [];
  this.negative = [];
  this.length = length;
  this.leftBound = leftBound;
  this.rightBound = leftBound + length

  if (this.leftBound < 0){
    this.negative.length = (leftBound * -1) + 1;
  } else {
    this.negative.length = 0;
  }
  if (this.rightBound >= 0){
    this.positive.length = rightBound + 1;
  } else {
    this.positive.length = 0;
  }

  this.watchObject = new ObjectWatcher(handler(prop, oldval, newval){ /* some stuff */ });

}

Then, when for example, if somebody did the following:

theLine = new DiscreteLine(-2, 4);
theLine[-8] = 10;

The handler would call, with the arguments ("-8", undefined, 10). (What would end up happening is, is that the script would recalculate leftBound and length properties automatically (like how Arrays automatically update the length property).

A: 

This would basically require overriding the setter for a property of an already defined object. As far as I know, this is only possible in ECMAScript 5 (via Object.defineProperty) and at the moment, I'm not sure which browsers support this, if at all, so it wouldn't be "cross-browser" as you had asked.

Edit: Your example makes your requirement clear now. I'm afraid the language doesn't provide any way to be notified when new properties are added to an object. In your example, you really don't have any choice except to replace the array notation with a function call.

casablanca
I don't see how one can create a watcher of all properties of an object using that method. Also, Firefox 4.0 will support it, at a minimum. It allows for changing key aspects of a property (something that is useful to me anyways), but not for watching the object.
Havvy