I am getting back a JSON data from an API and I want to compute the total cost for all the ‘cost’ field in the InvestmentSummary.InvestmentDetails array.
I am getting the following error:
Error: Unable to parse bindings.
Message: SyntaxError: invalid object initializer;
Bindings value: totalCost
My viewModel code looks like this:
var init = { InvestmentSummary: { InvestmentDetails: [] } };
ko.mapping.fromJS(init, {}, self);
self.totalCost = ko.computed({
read: function () {
var result = 0;
ko.utils.arrayForEach(self.InvestmentSummary.InvestmentDetails, function () {
result += item.Cost();
});
return result;
}
},self);
self.createBtnClick = function () {
self.layoutView(true);
var investAPI = "some_api";
$.getJSON(investAPI, function (result) {
ko.mapping.fromJS(result, {}, self);
});
};
My JSON data looks like:
{
InvestmentSummary: {
InvestmentDetails: [
{
Cost: 0
},
{
Cost: 1
}]
}
}
What am I doing wrong? Thanks
Hard to tell without your full structure, but here are a couple of things that you would want to update:
InvestmentDetailswill be an observableArray after going through mapping, so in yourarrayForEachyou will want the first argument to beself.InvestmentSummary.InvestmentDetails(), so that you can loop on the underlying array.in the function being run on each detail, you are accessing
item.Cost(), you will need to passiteminto that function as the only argument.when you are updating the data with the mapping plugin, you can omit the second argument (mapping options), if the structure has already been created.
Here is a fiddle with these updates: http://jsfiddle.net/rniemeyer/6dqfC/