views:

32

answers:

1

A simple example using a built-in javascript object: navigator.my_new_property = "some value"; //can we detect that this new property was added?

I don't want to constantly poll the object to check for new properties. Is there some type of higher level setter for objects instead of explicitly stating the property to monitor?

Again, I don't want to detect if the property value changed, but rather when a new property is added.

Ideas? thanks

+2  A: 

Nope. The existing methods of determining when a property gets written to:

  • an ECMAScript 5 setter defined using defineProperty(obj, name, fn);
  • a legacy JavaScript setter defined using __defineSetter__(name, fn);
  • a legacy Netscape/Mozilla watch(name, fn);

are all name-based, so can't catch a new property being written with a previously-unknown name. In any case, navigator may be a ‘host object’, so you can't rely on any of the normal JavaScript Object interfaces being available on it.

Polling, or explicit setter methods that provide callback, is about all you can do.

Similar situation: http://stackoverflow.com/questions/2449182/getter-setter-on-javascript-array

bobince
Thanks for the detailed response.If I go the polling route, what would you consider to be a good interval in ms? Obviously I would want it to be effective but not repeat unnecessarily. Is there a "standard" interval that some of the frameworks use for their polling?Suggestions are appreciated.
UICodes
I think it would depend on exactly what you're aiming to do; there's no one answer. What object are you polling, how often do you expect it to change, how many other properties are defined on it to go through? Whilst you could get away with a very small interval like 50ms on a modern desktop browser, for a well-populated object on a weak browser like IEMobile6 that could bring it to its knees! Incidentally, for the host objects like `navigator` there's not even any guarantee that setting any new properties, or using `for...in` to iterate over them, will work! :-S
bobince