mardi 18 octobre 2016

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 - </span>
<span>Some text - </span>
<span>Some text - </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 - </span>
<span>Some text - </span>
<span>Some text - </span>

Is it possible to do with emberjs and handlebars?




Aucun commentaire:

Enregistrer un commentaire