我有两个模型,一个与另一个具有hasMany关系:
配送费:
import DS from 'ember-data';
export default DS.Model.extend({
pickup_address: DS.belongsTo('address', { inverse: null }),
delivery_address: DS.belongsTo('address', { inverse: null }),
shipment_lines: DS.hasMany('shipment-line', { inverse: null }),
shipmentPrice: Ember.computed('shipment_lines.@each.package_price', function () {
let price = 0;
this.get('shipment_lines').forEach(function(shipment_line) {
price += Number(shipment_line.get('package_price'));
});
return price;
}),
});
和装运线型号:
import DS from 'ember-data';
export default DS.Model.extend({
description: DS.attr('string'),
package_weight: DS.attr('number'),
package_length: DS.attr('number'),
package_width: DS.attr('number'),
package_height: DS.attr('number'),
package_price: DS.attr('number'),
});
在控制器中,当我向货件添加新的装运行时,我从API获取包裹的价格并将其添加到装运行:
addShipmentLine(shipmentLine) {
// Get price for shipment line
this.getShipmentLinePrice(shipmentLine);
// Add shipment line to shipment
let shipment = this.get('shipment');
shipment.get('shipment_lines').addObject(shipmentLine);
},
getShipmentLinePrice函数(简化):
getShipmentLinePrice(shipmentLine) {
...
// Get weight and type
let weight = shipmentLine.get('package_weight');
let length = shipmentLine.get('package_length');
let height = shipmentLine.get('package_height');
let width = shipmentLine.get('package_width');
// Fetch price from API
this.get('price').getPackagePrice(weight, length, height, width).then(
(price) => {
shipmentLine.set('package_price', price['price']);
}
);
}
最后,当我尝试在模板中打印shipmentPrice
时,它不会更新。即使价格是从服务器返回的,并且设置了shipment_line
s package_price
。
此外,当我使用shipment.save();
保存货件并且路线被重定向到展示页面时,价格会翻倍,直到我刷新页面。页面刷新后,一切都正确显示。
所以第一个问题是,在添加新的装运线对象时,如何让装运计算属性shipmentPrice更新?或者是不可能的?
第二个问题是,为什么保存后价格会翻倍?
答案 0 :(得分:0)
尝试:
shipmentPrice: Ember.computed('shipment_lines.[]', function () {
let price = 0;
this.get('shipment_lines').forEach(function(shipment_line) {
price += Number(shipment_line.get('package_price'));
});
return price;
}),
答案 1 :(得分:0)
我终于想到了这一个。好吧,至少我找到了解决方法。保存模型后,我手动将shipmentPrice
重置为0
:
freight_order.save().then(
(new_freight_order) => {
shipment.set('shipmentPrice', 0);
this.transitionToRoute('shipments.show', new_freight_order.id);
}
);
我猜服务器响应由于某种原因被添加到计算值中。