具有模型属性的Ember计算 [英] Ember calculation with model attributes
问题描述
我想计算一个票价的总结果。您可以在这里看到: http://emberjs.jsbin.com/yudofozoqu/1/
I want to calculate the total result for a fare. You can see here: http://emberjs.jsbin.com/yudofozoqu/1/
它由价值数量组成:
{{input value=quantity}}
乘以可在选择选项中选择的具体票价:
multiplied by the specific fare which can be selected in the select option:
{{view Em.Select prompt="test" contentBinding="controllers.fare.content" optionLabelPath="content.name" optionValuePath="content.id" selectionBinding="controllers.fare.selectedFare" }}
总结果必须对应到我在我的模型中设置的总价值:
The total result has to correspond to the total value I have set up in my model:
{{input value=total}}
App.Invoice = DS.Model.extend({
name : DS.attr('string'),
quantity : DS.attr('string'),
total : DS.attr('string')
});
App.Invoice.FIXTURES = [
{
id: 1,
quantity: null,
total: null
}
];
如何正确执行?
推荐答案
您需要创建一个函数来观看数量
和 fare.selectedFare $中的更改c $ c>属性,所以它可以计算总数。例如:
You need to create a function to watch for changes in the quantity
and fare.selectedFare
properties so it can calculate the total. For example:
// this should be added to the IndexController
updateTotal: function() {
// get the reference to the values of fare and quantity
var quantity = this.get('quantity'),
fare = this.get('controllers.fare.selectedFare.id');
// massage them to make sure your stuff is not gonna break
if (isNaN(fare)) { fare = 0; }
if (isNaN(quantity)) { quantity = 0; }
// calculate
var total = fare * quantity;
// set the total
this.set('total', total);
}.observes('quantity', 'controllers.fare.selectedFare')
确定。这样做有效,但考虑在后台保存记录(在服务器控制器中)进行总计算,并将总计
属性转换为具有相同概念的计算属性的代码。根据你在做什么,如果它涉及到浮点数/十进制/异常计算,(我倾向于认为),你可以期待更多的精度与静态类型(通常在服务器上)而不是JavaScript
Ok. This works, but consider doing the total calculation in the backend as you save the record (in your server controller) and turn the total
attribute into a computed property with the same general idea of the code above. Depending on what you are doing, if it involves float/decimal/exotic calculations, (I tend to think that) you can expect more accuracy with static types (generally on the server) instead of JavaScript
这篇关于具有模型属性的Ember计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!