UICodes
UICodes

Reputation: 141

Detect when a new property is added to a Javascript object?

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

Upvotes: 9

Views: 3260

Answers (2)

niryo
niryo

Reputation: 1545

ES6 introduces the concept of Proxies: es6 proxies on MDN.

Here is a simple example:

let objectToSpy = {};
let handler = {
    set: (target, prop, value)=>{
        console.log('new prop:', prop);
        target[prop] = value;
    }
};

let proxy = new Proxy(objectToSpy,handler);
proxy.testProp = 'bla'; //prints: "new prop: testProp"

Upvotes: 5

bobince
bobince

Reputation: 536359

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: Getter/setter on javascript array?

Upvotes: 7

Related Questions