Computed Properties

Define new properties using computed properties

Computed properties let you declare a function as a property that can be accessed from within your template as well as from within your component.

They are used to take normal properties (e.g., data that is returned by your integration in block.data.details) and manipulate or transform them.

As an example, the following is a computed property that takes a firstName and lastName property and returns a fullName.

component.js
'use strict';

polarity.export = PolarityComponent.extend({
    fullName: Ember.computed('block.data.details.firstName', 'block.data.details.lastName',
        function(){
            return `${this.get('block.data.details.firstName')} 
                ${this.get('block.data.details.lastName')}`;
    })    
});

The first argument or arguments are strings which define the properties that the computed property is dependent on. Anytime any of the properties change in value, the computed property is recomputed. In the example above, the computed property fullName is dependent on the block.data.details.firstName and block.data.details.lastName properties.

Once you have created a computed property you can access that value directly within your templates using the curly brace syntax.

template.hbs
<div>
    fullName: {{fullName}}
</div>

You can also access the computed property within the component and create computed properties based on computed properties. Anytime the firstName or lastName values change the fullName computed property is updated. When the fullName computed property gets updated the fullNameLower property will also get updated.

'use strict';

polarity.export = PolarityComponent.extend({
    fullName: Ember.computed('block.data.details.firstName', 'block.data.details.lastName',
        function(){
            return `${this.get('block.data.details.firstName')} 
                ${this.get('block.data.details.lastName')}`;
    }),    
    fullNameLower: Ember.computed('fullName', function(){
        return this.get('fullName').toLowerCase();    
    })        
});

For more information on computed properties please see https://guides.emberjs.com/v3.4.0/object-model/computed-properties/

Last updated