Reputation: 276
Can I use ES6 Proxy to observe object, getting and setting properties etc? For example:
var obj = {a: 1; b: 2};
obj.a = 3; // I need to catch this setting, like a Object.watch() in Firefox
Upvotes: 1
Views: 3055
Reputation: 45
Why not to use getters/setters of object?
let ourObj = {
get a(){
return this._a;
}
set a(val){
console.log(val);
this._a = val
}
}
Upvotes: -1
Reputation: 1074268
Yes, that's part of what they're for. The trap you're looking for is called set
:
let obj = {a: 1, b: 2};
let p = new Proxy(obj, {
set(target, name, value) {
console.log("set " + name + " to " + value);
target[name] = value;
}
});
p.a = 3;
Upvotes: 5