Computed Properties

What are Computed Properties?

In a nutshell, computed properties let you declare functions as properties.
You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property.
You can then use it the same way you would any normal, static property.

It's super handy for taking one or more normal properties and transforming or manipulating their data to create a new value.

Computed properties in action

We'll start with a simple example.
We have a Person object with firstName and lastName properties, but we also want a fullName property that joins the two names when either of them changes:

This declares fullName to be a computed property, with firstName and lastName as the properties it depends on.
The first time you access the fullName property, the function will be called and the results will be cached.
Subsequent access of fullName will read from the cache without calling the function.
Changing any of the dependent properties causes the cache to invalidate, so that the computed function runs again on the next access.

Multiple dependents on the same object

In the previous example, the fullName computed property depends on two other properties:

Chaining computed properties

You can use computed properties as values to create new computed properties.
Let's add a description computed property to the previous example,
and use the existing fullName property and add in some other properties:

So this change to firstName was observed by fullName computed property, which was itself observed by the description property.

Setting any dependent property will propagate changes through any computed properties that depend on them, all the way down the chain of computed properties you've created.

Setting Computed Properties

You can also define what Ember should do when setting a computed property.
If you try to set a computed property, it will be invoked with the key (property name), and the value you want to set it to.
You must return the new intended value of the computed property from the setter function.