依赖属性更改时,Ember计算属性不会更新

时间:2016-03-08 05:45:32

标签: javascript ember.js

我是ember.js的新手,为了了解我正在尝试在ember中构建一个简单的应用程序。该应用程序是一个简单的卡路里计数器,可跟踪每餐(不记得用餐名称,我使用faker为模拟数据生成随机名称),

enter image description here

在列表底部有一个组件(food-input meal 3)输入,你输入名称然后点击回车并添加新餐,ember更新DS.RecordArray所以新的餐将立即显示在列表中。

food-input组件显示的膳食数量取决于列表中的最后一餐,它获取最后一餐的膳食数量加上1,逻辑处于计算属性(newNumber)中绑定到模板中的元素。

这是来自food-input js file

的代码
import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'tr',
  newNumber: Ember.computed('meals', function() {
   console.log('newNumber updated');
   return this.get('meals').get('lastObject').get('number') + 1;
  }),
  actions: {
    addMeal(newMeal) {
      if(newMeal) {
        this.sendAction('action', this.get('newNumber'), newMeal);
      }
      this.set('newMeal', '');
    }
  }
});

这是food-input模板

<td class="title">meal {{newNumber}} {{input type="text" placeholder="name" value=newMeal enter="addMeal" class="input"}}</td>
<td colspan="6"></td>
<td class="title"></td>

这里是使用food-input的路线模板

<h3>calorie tracking</h3>
{{#food-list}}
  {{#each model as |group|}}
    {{#food-group meal=group deleteMeal="deleteMeal" updateMeal="updateMeal"}}
      {{#each group.foods as |food|}}
        {{food-item title=food.name calorie=food.calorie carbs=food.carbs protein=food.protein fat=food.fat}}
      {{/each}}
    {{/food-group}}
  {{/each}}
  {{food-input action="createMeal" meals=model}}
{{/food-list}}

逻辑很简单,模型(膳食列表)在food-input中传递,计算属性newNumber获取最后一餐数加1,属性绑定到模板,因此同步将是自动的。因此,结果是当您添加新膳食时,food-input的号码会相应增加。

问题是它只在应用程序第一次加载时才有效,我可以在应用程序启动时看到console.log('newNumber updated');的输出,当我添加新餐时,计算属性永远不再运行(我无法做到)再次查看console.log输出),因此新餐和food-input将以相同的餐数结束。我认为该属性依赖于引用模型的meals,因此当模型更改时,属性应该更新,但它不会那样工作。我很贪图,所以我不知道我错过了什么,所以请帮忙。

1 个答案:

答案 0 :(得分:2)

当数组成员发生更改时,您需要重新计算计算属性,而不是数组本身(即完全换出)。将.[]添加到从属密钥的末尾以执行此操作。

newNumber: Ember.computed('meals.[]', function() {})

相关问题