EmberJS从父模型中设置defaultValue

时间:2014-10-27 07:35:35

标签: javascript ember.js ember-data

我需要将defaultValue的price属性设置为item的价格。我不想使用ComputedProperty,因为当我的商品价格发生变化时,我的transaction_detail的价格也会发生变化,我的情景第一次设置为price值&不应该改变。

这是我的TransactionDetail.js。

var TransactionDetail = DS.Model.extend({
  transaction: DS.belongsTo('transaction'),
  item: DS.belongsTo('item', { async: true }),
  borrowed_at: borrowedAt,
  max_returned_at: maxReturnedAt,
  returned_at: DS.attr('date'),
  price: DS.attr('number', {
    defaultValue: function( detail) {
      return detail.get('item.price'); // EXPECT TO GET ITEM'S PRICE, BUT ACTUAL IS NULL
    }
  }),
});

以下是我的Item.js

var Item = DS.Model.extend({
  name: DS.attr('string'),
  is_available: DS.attr('boolean', { defaultValue: true }),
  price: DS.attr('number', { defaultValue: 0 })
});

更新 在我阅读this后,我在initializers/reopen-store.js上添加文件并编辑内容,如下所示:

import DS from 'ember-data';

export function initialize(container, application) {
  var store = container.lookup('store:main');

  store.reopen({
    createRecord: function(type, properties) {
      if (type === 'transactionDetail') {
        if (typeof properties.price !== 'number') {
          properties.price = properties.item.get('price');
        }
      }

      return this._super.apply(this, arguments);
    }.on('createRecord')
  });

};

export default DS.Store.extend({
  name: 'reopen-store',
  initialize: initialize
});

但是当我在模型上debugger;时,this.get('item.price')仍为undefined。有什么想法吗?

更新2:

感谢GJK的回复。但你的回答对我来说仍然没有运气。 这是我的app/store.js

import DS from 'ember-data';

export default DS.Store.extend({
    init: function() {
        console.log('Init called!');
        return this._super.apply(this, arguments);
    },
    createRecord: function(type, properties) {
      console.log('Prepare createRecord!');
      debugger;

      if (type === 'transactionDetail') {
        if (typeof properties.price !== 'number') {
          properties.price = properties.item.get('price');
        }
      }

      return this._super.apply(this, arguments);
    }
});

在我的控制台中,输出只是Init called!。我的Chrome中未触发'Prepare createRecord!'debugger。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

defaultValue函数中,item.price即将出现null,因为item关系可能尚未初始化。就个人而言,我会在您创建记录时在商店中处理此问题,而不是在模型中。

App.Store = DS.Store.extend({
    createRecord: function(type, properties) {
        if (type === 'transactionDetail') {
            if (typeof properties.price !== 'number') {
                properties.price = properties.item.get('price');
            }
        }

        return this._super.apply(this, arguments);
    }
});

可能需要更多的错误检查,但你明白了。如果在创建时没有给出价格,请将其填入并让商店处理剩下的工作。

相关问题