Knockout.js 如何在knockoutjs中创建具有返回值的函数

Knockout.js 如何在knockoutjs中创建具有返回值的函数,knockout.js,Knockout.js,这是我的项目模型: var itemModel = function (id,description,picture,totalInventory,retailPrice,dealerPrice,category,brand,unitOfMeasure,createdBy,status,highestCost, lowestCost) { var self = this; self.ID = ko.observable(id); self.Description = ko.observable

这是我的项目模型:

var itemModel = function (id,description,picture,totalInventory,retailPrice,dealerPrice,category,brand,unitOfMeasure,createdBy,status,highestCost, lowestCost) {
var self = this;

self.ID = ko.observable(id);
self.Description = ko.observable(description);
self.Picture = ko.observable(picture);
self.TotalInventory = ko.observable(totalInventory);
self.RetailPrice = ko.observable(retailPrice);
self.DealerPrice = ko.observable(dealerPrice);
self.Category = ko.observable(category);
self.Brand = ko.observable(brand);
self.UnitOfMeasure = ko.observable(unitOfMeasure);
self.CreatedBy = ko.observable(createdBy);
self.Status = ko.observable(status);
self.HighestCost = ko.observable(highestCost);
self.LowestCost = ko.observable(lowestCost);};
我有这个方法来获取项目

self.GetItems = function(){
   $.getJSON("/Items/GetItems",{status: self.ItemStatus()}, function (result) {
      for (var i = 0, j = result.data.length; i < j; i++){
            item = result.data[i];
            underlyingArray.push(new itemModel(
                item.ID,
                item.Description,
                item.Picture,
                ....computetotalinventoryhere...,
                item.RetailPrice,
                item.DelearPrice,
                item.Category,
                item.Brand,
                item.UnitOfMeasure,
                item.CreatedBy,
                item.Status,
                item.HighestCost,
                item.LowestCost
            ));
        }
        self.list.valueHasMutated();
   }
self.GetItems=function(){
$.getJSON(“/Items/GetItems”,{status:self.ItemStatus()},函数(结果){
对于(var i=0,j=result.data.length;i
})


我想创建一个函数来计算总库存量。这在淘汰赛中可能吗?或者关于如何实现这一点的任何建议。谢谢。

使用计算的可观察值

var totalInv = ko.computed(function(){
   var total = 0;
   for(var i = 0; i < underlyingArray().length; i++){
       total += underlyingArray()[i].RetailPrice; // OR OTHER VALUES AS NEEDED
   }

   return total;  // or other values as needed
});
var totalInv=ko.computed(函数(){
var合计=0;
对于(var i=0;i
如果必须使用ES5,我建议使用map/reduce,而不是带有外部总变量“return underyingarray().map(~selectorFn~).reduce(函数(prev,curr){return prev+curr;},0)的for循环underlyingArray变量从何而来?在for循环之前是否缺少赋值?是“self.list”中所有项的合计,还是每个itemModel都有自己的合计值,高于我设置变量var item的合计值,underlyingArray=self.list();其他问题呢……这可能会影响答案。我编辑了上面的脚本。我添加了itemModel。