Reputation: 141
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
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
Reputation: 536359
Nope. The existing methods of determining when a property gets written to:
defineProperty(obj, name, fn)
;__defineSetter__(name, fn)
;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