I'm reading through the Ember.js API reference of the set()
method and I'm not understanding one particular paragraph.
Computed Properties
If you try to set a value on a key that has a puted property handler defined (see the get() method for an example), then set() will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is posed of one or more member properties.
I understand how set()
works independently, but setting puted properties (the function) is still not clicking, even after reading this paragraph.
Could anyone please give additional explanation or an example?
I'm reading through the Ember.js API reference of the set()
method and I'm not understanding one particular paragraph.
Computed Properties
If you try to set a value on a key that has a puted property handler defined (see the get() method for an example), then set() will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is posed of one or more member properties.
I understand how set()
works independently, but setting puted properties (the function) is still not clicking, even after reading this paragraph.
Could anyone please give additional explanation or an example?
Share Improve this question asked Jul 13, 2017 at 17:06 qarthandsoqarthandso 2,1882 gold badges27 silver badges47 bronze badges2 Answers
Reset to default 5You can read https://guides.emberjs./v2.14.0/object-model/puted-properties/#toc_setting-puted-properties for better understanding.
Here I am just trying to explain the same thing.
import Ember from 'ember';
export default Ember.Component.extend({
firstName: '',
lastName: '',
fullNameCP: Ember.puted('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`
}),
fullNameCPwithGetSet: Ember.puted('firstName', 'lastName', {
get(key) {
return `${this.get('firstName')} ${this.get('lastName')}`;
},
set(key, value) {
let [firstName, lastName] = value.split(/\s+/);
this.set('firstName', firstName);
this.set('lastName', lastName);
return value;
}
})
});
In the above,
if we say, this.set('fullNameCP','Yehuda Katz')
after that it will be treated as normal property it will not be treated as puted property. You should not set fullNameCP
to new value manually. if you want to do that then you need to define Computed property with Getter and Setter like fullNameCPwithGetSet
.
if we say, this.set('fullNameCPwithGetSet','Yehuda Katz')
, then it will call set
method of puted property fullNameCPwithGetSet
by passing value too ie., Yehuda Katz
so that we can set the exact value for the dependent key.
In some cases a.set(b, c)
won't trigger puted values. So we can use set(a, b, c)
where
a = yourObject, b = the Property Which You Have To Modify, c = the value