An attribute that can accept both API response and computed


#1

Hello, I am using the following version of Ember:

DEBUG: -------------------------------
DEBUG: Ember      : 2.8.2
DEBUG: Ember Data : 2.8.1
DEBUG: jQuery     : 2.1.4
DEBUG: -------------------------------

I want a field behave like this: if my server response has field’s value, use it, else compute it using comput property. For example something like this:

// human.js
import DS from 'ember-data';
export default DS.Model.extend({
  money: DS.attr('number'),
  rich: DS.attr('boolean'),
  rich: Ember.computed.gt('money', 1000000)
});

Then this human is rich either determine by API or computed by money he has.


#2
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import computed from 'ember-computed';
import { isEmpty } from 'ember-utils';

export default Model.extend({
  money: attr('number'),
  rich: attr('boolean'), 
  richComputed: computed('money', 'rich', function() {
     return isEmpty(this.get('rich')) ? this.get('money') > 1000000 : this.get('rich');
  })
});

and use richComputed instead rich


#3

Nice approach. Although it sounds a hack to me, it works.