Crabar Crabar - 1 month ago 11
Javascript Question

Get rid of code repeating in computed properties

I have a next code in my component:

firstIngredientName: Ember.computed('suggestedIngredients.[]', function() {
const store = this.get('simpleStore');
if (this.get('suggestedIngredients.length') > 0) {
let sugIngredient = this.get('suggestedIngredients').objectAt(0);
let ingredient = store.find('ingredient', sugIngredient.get('ingredientId'));
return ingredient.get('name');
}
}),
secondIngredientName: Ember.computed('suggestedIngredients.[]', function() {
const store = this.get('simpleStore');
if (this.get('suggestedIngredients.length') > 1) {
let sugIngredient = this.get('suggestedIngredients').objectAt(1);
let ingredient = store.find('ingredient', sugIngredient.get('ingredientId'));
return ingredient.get('name');
}
}),
thirdIngredientName: Ember.computed('suggestedIngredients.[]', function() {
const store = this.get('simpleStore');
if (this.get('suggestedIngredients.length') > 2) {
let sugIngredient = this.get('suggestedIngredients').objectAt(2);
let ingredient = store.find('ingredient', sugIngredient.get('ingredientId'));
return ingredient.get('name');
}
})


As you see each property similar to another, only difference is in a array index.

Here is my template:

<span>Some text - {{firstIngredientName}}</span>
<span>Some text - {{secondIngredientName}}</span>
<span>Some text - {{thirdIngredientName}}</span>


It really hurts to write such repeating code so I try to find a way to simplify my component. I want get something like next:

<span>Some text - {{ingredient 0}}</span>
<span>Some text - {{ingredient 1}}</span>
<span>Some text - {{ingredient 2}}</span>


Is it possible to do with emberjs and handlebars?

Answer

-You can calculate ingredientNames array in single computed propery and access it using each block helper in hbs.

ingredientNames: Ember.computed('suggestedIngredients.[]', function() {
        let ingredientNamess = [];
        const store = this.get('simpleStore');
        if (this.get('suggestedIngredients.length') > 0) {
            for (var i = 0; i < 3; i++) {
                var sugIngredient = this.get('suggestedIngredients').objectAt(i);
                if (Ember.isPresent(sugIngredient)) {
                    var ingredient = store.find('ingredient', sugIngredient.get('ingredientId'));
                    ingredientNamess.push(ingredient.get('name'));
                }
            }
        }
        return ingredientNamess;
    }),

-Another approach you can create helper and pass suggestedIngredients and index and that should return the result.