问题
I am working on a simple Ember app that shows ID's for list elements. The ID's are computed with simple functions based on the element sequence (and some other simple factors). For example:
<div class="content-id element">[ELEMENT ID]</div>
<div class="content-name">{{element.name}}</div>
I don't want to hardcode the element id's into the JSON object, but rather compute them in a simple function. Would it be best to place this function in the route object or in the component? What's the syntax?
Thank you.
回答1:
If you want to compute something based only on model properties, you should use a computed property. In following example I define a computed property citiesString
:
import DS from 'ember-data';
import Ember from 'ember';
export default DS.Model.extend({
name: DS.attr('string'),
cities: DS.hasMany('city', { async: false }),
citiesString: Ember.computed('cities', function () {
var cities = [];
this.get('cities').forEach(function (item, index, enumerable) {
cities.push(item.get('name'));
}, this);
return cities.join(', ');
})
});
You can use computed property like any other:
{{#each elements as |element index|}}
{{element.citiesString}}
{{/each}}
If you want to use element's index (if I understand "element sequence" right), I can't think out other way than writing a helper, pass to it element, index, and return ID. Example of helper:
//app/helpers/my-helper.js
import Ember from 'ember';
export default Ember.Handlebars.makeBoundHelper(function (element, index) {
return index; //do something useful instead of this
});
How to use it:
{{#each elements as |element index|}}
{{my-helper element index}}
{{/each}}
You should keep in mind that index can change (as can order of element in array) and different users may see different ID for the same element.
来源:https://stackoverflow.com/questions/32235795/where-and-how-to-include-ember-model-functions