【发布时间】:2017-05-08 23:16:10
【问题描述】:
我有一个从 ajax 调用返回的对象,我想从这个对象做一些计算,这取决于用户的输入。输入是数字输入和复选框,以在计算中包含另一个数字。
我的 JS 是:
var viewModel = function()
{
var self = this;
self.currentVal = ko.observable(2);
self.includeTax = ko.observable(false);
self.sales = ko.observableArray([]);
self.computedSales = ko.observableArray([]);
self.sales([
{"ProductID": "10121a", "Cost": 110, "Quantity": 6, "X": 9034.25, "Other": 23, "Date": 2017-05-5},
{"ProductID": "10122b", "Cost": 10, "Quantity": 18, "X": 152.99, "Other": 20, "Date": 2017-05-3},
{"ProductID": "10123c", "Cost": 1000, "Quantity": 2, "X": 99.50, "Other": 5, "Date": 2017-05-1}]);
self.computeSales = function() {
ko.utils.arrayForEach(self.sales(), function (item) {
self.computedSales().push({
"ProductID": item.ProductID,
"Total": item.Cost * item.Quantity,
// "Total" is needed for the Calc value, is there a way to re-use the Total without having to duplicate it below?:
// "Calc": item.Cost * item.Quantity * (self.currentVal / 100)
"Calc": self.includeTax() == true ? (item.Cost * item.Quantity * (2 / 100) * .5) : (item.Cost * item.Quantity * 2 / 100)
});
//alert(self.computedSales()[self.computedSales().length -1].Total);
});
// self.currentVal not correct:
//alert(self.currentVal);
};
self.computeSales();
};
$(function () {
ko.applyBindings(new viewModel());
});
当我勾选复选框或更改输入中的值时,Calc 列没有改变 - 我做错了什么?
我的主要目标是找到一种方法来重用某些属性(例如 Total),而不必复制 item.Cost * item.Quantity,但我想这是另一个单独的问题。
任何帮助表示赞赏!
【问题讨论】:
标签: knockout.js