I am using Object.defineProperty
to override getter and setter on an object, so that I can listen to all the mutation events.
var a = {};
Object.defineProperty(a, key, {
get: function(){
..
},
set: function(val){
..
}
}
This works fine, but there's one caveat--I need to know in advance what attributes I want to listen to--which means I need to iterate through all the keys I want to watch in the beginning.
If I wanted to randomly assign a new attribute during runtime like this:
a.new_attr=1;
it wouldn't work because I haven't defined the new_attr
property yet.
Is there a way to either:
Object.defineProperty()
when I assign the attribute for the first time; or I think what you really want to use is a Proxy
. Proxies allow you to intercept events such as get and set.
var obj = { a: 1, b: 2 }; var proxiedObj = new Proxy(obj, { get: function(target, name) { console.log(`get: ${name}`); return target[name]; }, set: function(target, prop, value) { console.log(`set: ${prop}`); target[prop] = value; } }); console.log(proxiedObj.a); console.log(proxiedObj.b); // Notice that it still works even on new properties proxiedObj.c = 3; console.log(proxiedObj.c);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.