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 scenariothat's table i'm trying bind to

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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -