knockout.js - How to return the sum of two computed observable? -
i'm not familiar knockoutjs i'm trying sum of 2 computed observable , bind table:
i have this:
var cost = ko.computed(function () { total = 0; ko.utils.arrayforeach(claimtreatments(), function (item) { total += item.cost; }) return total; });
and,
var amount = ko.computed(function () { total = 0; ko.utils.arrayforeach(claimdrugs(), function (item) { total += item.drugcost; }) return total; });
and i'm trying not working.
var totalamount = ko.computed(function () { total = cost() + amount(); return total; });
also picture of table i'm trying bind to(the amount field), give clear idea of scenario
any appreciated!
just minor fixes trick here use self
. if want bind view . var
quite local viewmodel view doesn't quite recognize .
viewmodel:
var claimdrugs = [{'drugcost':10},{'drugcost':10},{'drugcost':10} ] claimtreatments = [{'cost':10},{'cost':10},{'cost':10} ] var viewmodel = function() { var self=this; self.cost = ko.computed(function () { total = 0; ko.utils.arrayforeach(claimtreatments, function (item) { total += item.cost; }) return total; }); self.amount = ko.computed(function () { total = 0; ko.utils.arrayforeach(claimdrugs, function (item) { total += item.drugcost; }) return total; }); self.totalamount = ko.computed(function () { total = self.cost() + self.amount(); return total; }); }; ko.applybindings(new viewmodel()); // makes knockout work
view :
<div > <p> <label data-bind='text: cost' ></label></p> <p> <label data-bind='text: amount' ></label></p> <h2><label data-bind='text: totalamount'> </label></h2> </div>
working fiddle here
ps: yes indeed can add 2 computed way doing binding view use above approach .
Comments
Post a Comment