I have an object returned from a ajax call and from this object I want to do some calculations on it, depending on inputs from the user. Inputs being a number input and checkbox to include another figure in the calculation or not.
My JS is:
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());
});
The Calc column does not change when I tick the checkbox nor change the value in the input - what am I doing wrong?
My main aim was to find a way to re-use some of the properties such as Total, instead of having to duplicate item.Cost * item.Quantity, but I guess this is another separate question.
Any help appreciated!