观察者不会在组件

时间:2016-02-07 11:18:16

标签: javascript ember.js

我在控制器中有下一个代码:

...
  selectedIngredientsIds: [],

  barItemsChanged: Ember.observer('user.barItems.[]', function() {
    let ingredients = [];
    if (this.get('user').get('barItems')) {
      ingredients = this.get('user').get('barItems').map(function(item) {
        return item.ingredientId;
      });
    }

    this.set('selectedIngredientsIds', ingredients);
  })
...

模板:

  {{ingredient-chooser
      multiple=false
      ingredients=ingredients
      changeIngredients="changeIngredients"
      needToClear=needToClear
      placeholder="Добавить в бар..."
      selectedIngredients=selectedIngredients
      selectedIngredientsIds=selectedIngredientsIds
      ingredientSelected="ingredientSelected" }}

成分选择器 组件:

...
  selectedIngredients: [],
  selectedIngredientsIds: [],

  selectedIngredientsChanged: Ember.observer('selectedIngredients.[]', function() {
    this.sendAction("changeIngredients", this.get('selectedIngredients'));
  }),

  selectedIngredientsIdsChanged: Ember.observer('selectedIngredientsIds.[]', function() {
    let self = this;
    let ingredients = this.get('selectedIngredientsIds').map(findIngredientByRealId);
    this.set('selectedIngredients', ingredients);
  })
...

barItemsChanged观察员工作正常。 selectedIngredientsChanged也可以。即使我检查selectedIngredientsIds属性,它也会显示正确的值。但由于某些原因selectedIngredientsIdsChanged观察者从未打过电话。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我修复了下一个代码的问题:

Ember.run.scheduleOnce('afterRender', this, () => {
      this.set('selectedIngredientsIds', ingredients);
    });

而不是:

this.set('selectedIngredientsIds', ingredients);

我想因为user.barItems是模型的一部分,所以在组件观察者初始化之前调用了barItemsChanged