Hello StackOverflow experts,
I would like to know if it would be possible to use Ember.js’ computed properties to modify the value of the property before returning to whatever object requests it.
Imagine this simple example:
I have a User object with mail property
When I set the property, I want the email address to change from first.last@example.com to first.last@anotherexample.com, then return it
When I request the property ( via User.get ) I want to get the modified property back.
I think it should be pretty simple by utilising another ‘helper’ property, like formatted_mail, where I would store and retrieve the formatted value, but I wonder if something like this can be done without additional model properties.
So far, I have this coffescript code, but I always get ‘undefined’ when reading the property, even though I set it before, so I suspect the value does not get saved by Ember anywhere:
mail: ( ( key, value ) ->
if arguments.length == 1
return this.get 'mail'
else
return value.split( '@' )[0] + '@anotherexample.com'
).property 'mail'
Thank you for your assistance!
You are close to solution.
As computed properties are always cached by default in Ember (you could disable this behaviour using
.volatile()), you do not have to specify what to do whenarguments.lengthis 1, except if you want to specify a default value.So here it should looks like:
The
return nulljust specify the default value.When you set the
mailproperty, it will cache the returned value and always returns it without recomputing this property.Note that you can do that only because the
mailproperty does not depend on other properties. If you were declaring it with.property('anotherProperty'), themailproperty will be recomputed any timeanoterPropertychanges. So in the example above it will reset it tonull.You can try it in this JSFiddle.