I wish to extend the Object and Array classes so that I will be able to listen to any changes made to their instances after construction.
The best I can do now is to add custom get and set functions for fields given at initialization/construction of an Instance:
var myObj = new CustomObject({name:'foo'});
myObj.name = 'bar'; // this will log "'name' in 'myObj' updated:'bar'"
//however:
myObj.age = 85; // this mutation will slip by unnoticed,
// since the 'age' field was never specified
// at initialization meaning no custom set / get
// functions where attached.
Is there a way to achieve the following functionality?
var myObj = new CustomObject();
myObj.name = 'foo';// this should log something like:
// "A new field 'name' was created for myObj with value 'foo'"
Note:I’m looking for a solution that doesn’t involve polling.
What I have now (resulting in the functionality shown in the first codeblock):
function CustomObject(data) {
var that = this;
for(var field in data){
prepField(field);
}
function prepField(field){
Object.defineProperty( that, field, {
set: function(val){
data[field] = val;
console.log(field,'in',that,'updated:',val);
},
get: function(){
console.log(field,'in',that,'requested');
return data[field];
},
enumerable:true
});
}
return this;
}
Thanks in advance!
Firefox (mozilla) has something called
Proxythat can do this.MDN Proxy docs
This is a non-standard feature currently, but appears as though it (or something similar) may become part of ECMAScript 6.
From http://wiki.ecmascript.org/doku.php?id=harmony:proposals :