Ember computed property is the most powerful thing ember has and here we are going to get overview of how we can make use of these properties.
Ember guides has explained it very nice way, and here I would like to add some more..
Bind property to nested resources
Many times we need to depend on nested resources for ex: Find the count of comments or likes for post OR find number of items in cart etc. Here we want to update property as its nested resource is changed.
Consider example: here we have property itemCount on cart, which should change as any item is added or deleted from cart. "@each" does that magic for us. It looks for any change in items of cart.
itemCount: function() { return this.get("items.length"); }.property('this.items.@each')
Magic of 'volatile'
Computed property is evaluated once and only changes when there is any change in the resource to which it is bonded. But there might be case where we want to observe localStorage and do not want to depend on its cached values, in that case we can use 'volatile'.
'volatile' sets computed property to use it into non-cached mode. In this mode, whenever property is called, it will compute value every time.
previewImageId: function() { return localStorage.favourite; }.property().volatile(),
How to render resolved promise value in Ember handlebars template
There might be case when we want some data from our api other than content we have in our ember-date store. So only way to get that data from api is from property. But is it possible to get response from property? will our property wait for response to resolve? yes, its possible.
Consider following example: here we want to display all the tags. Now when we call this property, at first it will return null value, but as the response is resolved, it will set back data from api to this property.
tags: function(key, value) { if (arguments.length > 1) { return value; } else { var sortConditions, _this = this; var store = this.get('targetObject.store'); store.find('tag').then( function(objs) { sortConditions = objs.sortBy('id'); _this.set("tags", sortConditions); value = sortConditions; }); return value; } }.property('tag.[]')
References for more information:
- Computed properties [here(link)][1]
- Computed properties and more.. [here(link)][2]
- Custom ember computed properties [here(link)][3]
- Nice stackoverflow answer with details [here(link)][4]
- Excellent blog on computed properties [here(link)][5]
[1]: http://emberjs.com/guides/object-model/computed-properties/
[2]: http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/
[3]: http://robots.thoughtbot.com/custom-ember-computed-properties
[4]: http://stackoverflow.com/a/24763801/2923156
[5]: http://reefpoints.dockyard.com/2013/09/04/computed_properties_in_ember_js.html