SteffenP
SteffenP

Reputation: 25

Ember computed property for object attribute

My component receives an object property named "line" and a string property named "name".

{{field-row line=model name=fieldName}}

The line object has several attributes. The following Ember computed property "value" returns the value based on the given line and name:

value: Ember.computed('line', function() {
    const line = this.get('line');
    const name = this.get('name');
    return line.get(name);
})

This works, but any updates to the line object's attribute won't automatically trigger a refresh on the component's template. I guess that's because the reference to the 'line' object remains the same while its attribute content changes. Since the name of the attribute can not be known beforehand, I tried this but it doesn't work either:

value: Ember.computed('line.@each', function() {
    const line = this.get('line');
    const name = this.get('name');
    return line.get(name);
})

Any ideas?

Upvotes: 2

Views: 4641

Answers (1)

mistahenry
mistahenry

Reputation: 8744

Edit: the following used to work but was not intended by the framework authors. Instead of using set, use defineProperty instead. See this issue

Well, if you know all of the possible attributes ahead of time, you can use the brace syntax:

value: Ember.computed('line.{length,width}', function(){
    var line = this.get('line');
    var name = this.get('name');
    return line.get(name);
  }) 

as this JSBIN demonstrates

But, if you want truly dynamic behavior:

export default Ember.Component.extend({

  value:null,
  initialize: function(){
    var name = this.get('name');
    var key = "line." + name;
    this.set('value', Ember.computed(key, function(){
    var line = this.get('line');
    var name = this.get('name');
    return line.get(name);
  }));
  }.on('init')

});

JSBIN numero dos

Upvotes: 7

Related Questions