I have a demo controller:
import Ember from 'ember';
export default Ember.Controller.extend({
firstName: 'Bob',
lastName: 'Smith',
emailAddress: 'bobsmith@gmail.com',
fullName: Ember.computed('firstName', 'lastName', function() {
console.log('executed!');
return `${this.get('firstName')} ${this.get('lastName')}`;
}),
actualEmailAddress: Ember.computed('emailAddress', function() {
console.log('actualEmailAddress function is called: ', this.get('emailAddress'));
})
});
When I'm running the app on localhost in the browser, I open ember inspector and run:
$E.get('actualEmailAddress')
This returns:
actualEmailAddress function is called: bobsmith@gmail.com
But when I run it a second time I just get undefined
Same thing when I run $E.get('fullName')
It returns
executed!
"Bob Smith"
But then when I run it again it only returns Bob Smith
, not the console.log
Why is this happening?
Thank you!
Computed properties only get computed on demand ie if its used in a template like {{actualEmailAddress}}
or used in js code as this.get('actualEmailAddress');
For performance computed properties only get recomputed if its dependent property values are changed. So after the first computation, the result is cached and if you try to access the CP again it will simply return the cached value.
In the first case for actualEmailAddress
, the CP function executed the first time and you got your statement logged but you are not returning a value hence undefined
is returned implicitly. So the next time you invoke the CP, the cached value undefined
is returned.
In the second case for fullName
, again the function is only invoked the first time and the statement is logged. Here since you have properly returned a value, the next time you try to invoke the CP, you get the cached return value as a response.
To force the CP to recompute you need to change the value of the dependent properties. Or use a simple method and invoke that.