Matt Mazzola
Matt Mazzola

Reputation: 5641

EmberJS Computed Properties only evaluated if they are used in the template?

I ran into a strange issue where my computed property was not executing. After some testing I realized that the other computed properties in the object were working fine and the only difference was that the working ones were rendered/used in the template.

I have created a JSBin to demonstrate. http://jsbin.com/izoyok/16/

Both properties have identical code and behavior. The only difference is that items1ComputedProperty is used in the template. And notice the computed property is logging messages into the console as expected.

Is this a requirement or optimization of ember to only spend time evaluating computed properties if they are renedered in the template? Or am I making some other mistake.

I could understand if they did this by design since it could be argued computed properties should be NOT used this way, and that you could use observers to assign a value to an instance property, but on the other hand I imagine a lot of people would not make the same assumption and I didn't see any documentation explaining the behavior.

http://emberjs.com/guides/object-model/computed-properties/

Upvotes: 1

Views: 599

Answers (1)

Mike Grassotti
Mike Grassotti

Reputation: 19050

It's not really a template thing. Computed properties are only executed when something attempts to use them. So when a template references a computed property, ember executes the function and caches the result. Then in future it uses the cache value unless one of the dependent properties have changed, in which case the cache is invalidated and the function will be executed again.

Upvotes: 3

Related Questions