Computed Properties

Say, there’s a array of objects I return from the route’s model. How to set the computed property for each of the object by iterating it ? Also, how to use the computed property in the template to print them? Refer the code sample for a better idea.

Also, where are the computed properties generally written ? In the Route’s model or the controller ?

Your code example is not valid JavaScript :slight_smile:

You can only define computed properties on an EmberObject, at extend time (not create time).

This is roughly how your example could work:

// app/my-route/route.js
import Route from '@ember/routing/route ';
import EmberObject, { computed } from '@ember/object';

const data = [...];

const Person = EmberObject.extend({
  firstname: null,
  lastname: null,
  fullname: computed('firstname', 'lastname', function() {
    return `${this.firstname} ${this.lastname}`;
  })
});

export default Route.extend({
  model() {
    return data.map((personData) => Person.create(personData));
  }
});
2 Likes

Also worth noting that, as you asked @JimParsons, CPs are typically defined in the controller. The controller is the only thing that the template “has access to”. In essence the route is there to load the model and manage transitions, the result of the model hook will be auto-injected into the controller as “model”, and the template then has access to “model” and any other controller properties or computed properties that you define on the controller.

2 Likes