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 computed 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 composed of one or more member properties.
I understand how set()
works independently, but setting computed properties (the function) is still not clicking, even after reading this paragraph.
Could anyone please give additional explanation or an example?
You can read https://guides.emberjs.com/v2.14.0/object-model/computed-properties/#toc_setting-computed-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.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`
}),
fullNameCPwithGetSet: Ember.computed('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 computed 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 computed property fullNameCPwithGetSet
by passing value too ie., Yehuda Katz
so that we can set the exact value for the dependent key.