Monday, June 3, 2024
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 34123  / 6 Years ago, wed, april 18, 2018, 12:00:00

is there a way to listen for a property call on a JavaScript Class



for example when i go something like this:



myForm =  new Form();

myForm.name = 'Name';


-> when i set the name i dont only want to set the property but i also want to update my Vuex store.
Same thing with get i would like to read from Vuex store.



I knoew there are thins like Proxy but for this i need to wrap my Class with a Proxy object. Not so sure if i like this.



module.exports = new Proxy(new Form({}), {
get (receiver, name) {
console.log('getting property from Vuex Store');
}
});


What i need is something like this:



module.exports = class Form {

//this should be triggered when form.something
get(property) {
return this[property];
}

//this should be triggered when from.something = 'something'
set(property, value) {
return this[property] = value;
}
};


it there a best practice for this?


More From » ecmascript-6

 Answers
18

Javascript supports getters and setters





class Form{
set foo(val){
console.log(setting foo)
this.fooValue = val;
}

get foo(){
console.log(getting foo);
return this.fooValue;
}
}

let frm = new Form();
frm.foo = bar;
console.log(frm.foo);





You could make this more dynamic by writing a withGetterSetter method which wraps each property of an object with a getter/setter.





var form = {
a: aValue,
b: bValue
}

function withGetterSetter(obj){
var keys = Object.keys(obj);
var result = {};

for(var i=0;i<keys.length;i++){
var key = keys[i];
result[key+_internal] = obj[key];
(function(k){
Object.defineProperty(result,k, {
get:function() {
console.log(getting property:,k);
return this[k + _internal];
},
set: function(x) {
console.log(setting property:,k);
this[k + _internal] = x
}
});
})(key)
}
return result;
}

var setterObj = withGetterSetter(form);
console.log(setterObj.a);
setterObj.a = updated;
console.log(setterObj.a);





It works by copying each property p to a new object with p_internal and creating a dynamic get/set for the original property name.


[#54633] Sunday, April 15, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;