摆脱计算属性中重复的代码

时间:2016-10-18 16:19:25

标签: javascript ember.js handlebars.js

我的组件中有下一个代码:

  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');
    }
  })

当你看到每个属性与另一个属性相似时,只有差异在于数组索引。

这是我的模板:

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

编写这样重复的代码真的很痛,所以我试图找到一种方法来简化我的组件。我希望得到类似的东西:

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

是否可以使用emberjs和把手?

1 个答案:

答案 0 :(得分:0)

- 您可以在单个计算机中计算ingredientNames数组,并使用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;
    }),

- 另一种方法是你可以创建帮助器并传递suggestIngredients和index,这应该返回结果。