lundi 7 mars 2016

Ember computed property doesn't update when dependent property changes

I am new to ember.js and in order to learn I am trying to build a simple app in ember. The app is a simple calorie counter that tracks each meal (never mind of the meal name, I'm using faker to generate random names for the mock data),

enter image description here

there is a component (food-input meal 3) for input on the bottom of the list, you type in the name and hit enter and it adds the new meal, ember updates DS.RecordArray so the new meal will show in the list instantly.

food-input component displays the meal number depends on the last meal in the list, it gets the meal number of the last meal and plus 1, the logic is in a computed property (newNumber) which is bound to the element in the template.

here is the code from 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', '');
    }
  }
});

here is the food-input template

<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>

here is the route template where food-input is used

<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}}

The logic is simple, the model(meal list) is passed in food-input, the computed property newNumber gets the last meal number and plus 1, the property is bound to the template so the sync will be automatic. So the result will be that when you add new meals food-input's number will increment accordingly.

The problem is that it only works when the app first loads, I can see the output of console.log('newNumber updated'); when the app starts, the computed property never runs again when I add new meals (I can't see console.log output again), so both the new meal and food-input will end up with the same meal number. I think the property depends on meals which references the model, so when model changes the property should update, but it doesn't work like that. I'm pretty new to ember so I have no idea what I missed, so please help.




Aucun commentaire:

Enregistrer un commentaire