2
votes

I like to know if there is way to use computed properties with ember data for example I would like to have totalPrice calculated and saved from based on amount of other properties. Only way I think I can think of doing it using an observer

1

1 Answers

4
votes

There is nothing different between an Ember data model and an ordinary Ember Object you can define computed properties on your models just like you do for your components, controllers, routes, etc. Please check the official ember guide. It has the following model example:

import DS from 'ember-data';
import { computed } from '@ember/object';

export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),

  fullName: computed('firstName', 'lastName', function() {
    return `${this.firstName} ${this.lastName}`;
  })
});

where fullName is defined as a computed property depending on firstName and lastName. Let's create an artificial model that contains totalPrice as you wanted:

import DS from 'ember-data';
import { computed } from '@ember/object';

export default DS.Model.extend({
  originalPrice: DS.attr('number'),
  vat: DS.attr('number'),
  discount: DS.attr('number')

  totalPrice: computed('originalPrice', 'vat', 'discount', function() {
    return this.originalPrice + this.vat - this.discount;
  })
});

something similar to above should simply work.

After the comment regarding sending the computed property to backend; sth. similar to below customization for serializer should work:

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  serialize(snapshot, options) {
    let json = this._super(...arguments);

    json.totalPrice = snapshot.record.get('totalPrice')

    return json;
  },
});