0
votes

I try to overwrite an ember-data model's save function:

models/client.js

export default DS.Model.extend({
  billingAddress: DS.belongsTo('address'),
  //...
  save: function(...arg){
    var _this = this;
    this.get('billingAddress').then(billingAddress=>{
      return billingAddress.save().then(function(){
        return _this._super(arg);
      });
    })

  }
});

Somewhere else I do

record.save().then(function(){
  // show a message
});

I am getting the following error:

Uncaught TypeError: Cannot read property 'then' of undefined

SOLUTION

The main problem was that calling super from a promise is not that straight forward, but is possible:

  save: function(...arg){
    let _super = this._super;
    return somePromise.then(() => _super.call(this));
  }
2

2 Answers

1
votes

This is indeed a common pattern but I wouldn't overwrite the model's save method, instead I would handle it on the level of the route/controller.

import Ember from 'ember';

const { Mixin, RSVP: { resolve } } = Ember;

Ember.Mixin.create({
  beforeSave() {
    return resolve();
  },
  save() {
    this.beforeSave().then(() => this.get('currentModel').save());
  },
  {
    actions: {
      save() {
        this.save();
      }
    }
  }
});

You would add that mixin to your routes, if you add it to the controller currentModel becomes model, and overwrite beforeSave to deal with your relationships, make sure you return a promise from beforeSave.

0
votes

Your Save implementation does not return anything. I think you have to return the promise returned from "_this._super(arg);"

export default DS.Model.extend({
  billingAddress: DS.belongsTo('address'),
  //...
  save: function(...arg){
    var _this = this;
    return this.get('billingAddress').then(billingAddress=>{
      return billingAddress.save().then(function(){
        return _this._super(arg);
      });
    })

  }
});