Computed property doesn't work as expected


#1

Hi, guys! I stuck on the next problem. I have a component with a “chosen” input where user can select multiple options. I want to map list of selected ids to list of another ids and send them to parent controller. How it looks now:

components/filter-menu.js

import Ember from 'ember';

export default Ember.Component.extend({
  selectedFakeIngredients: [],

  selectedRealIngredients: Ember.computed('selectedFakeIngredients', function(key, value) {
    var self = this;
    if (arguments.length > 1) {
      return value;
    }
    return this.get('selectedFakeIngredients').map(function(item) {
      return self.get('filteredIngredients')[item].groupId;
    });
  }),

  actions: {
      doSearch() {
        this.sendAction("doSearch");
      }
  }
});

templates/components/filters-menu.hbs

{{ember-chosen multiple=true searchContains=true displaySelectedOptions=false content=filteredIngredients optionValuePath="id" optionLabelPath="caption" value=selectedFakeIngredients action="doSearch" placeholder="Напишите ингредиент..."}}

templates/builder.hbs

{{filters-menu clearFilters="clearFilters" doSearch="doSearch" toggleType="toggleType" toggleOption="toggleOption" selectedRealIngredients=selectedIngredients ingredients=ingredients}}

When I just set directly “selectedFakeIngredients” in builder.hbs all works fine (expect these are incorrect ids). But if set computed property “selectedRealIngredients” it is not working at all. “selectedRealIngredients” function not called. Am I doing something wrong? Is there another way to achieve needed behaviour?

P.S. I’m using last stable version of EmberJS.


#2

Computed properties like this are (sort of) read-only. Setting them will not invoke the function, it will just overwrite them with whatever you set.

You must pass an object with separate get and set method to make it respond to sets:

selectedRealIngredients: Ember.computed('selectedFakeIngredients', {
    get: function (key) {
        return something;
    },
    set: function (key, value) {
        do_something();
        return new_value;
    }
})

#3

Thanks for advice. I will try this syntax in my code. I resolved problem with the next piece of code:

...Ember.computed('selectedFakeIngredients.[]'...