2014-03-04 32 views
0

返回值的函数,这是我itemModel:如何创建与knockoutjs

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(); 
    } 

};

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

+0

哪里underlyingArray变量从何而来?你在for循环之前缺少一个赋值吗?是否在“self.list”中的所有项目之间的总数或每个itemModel都有其自己的总值 –

+0

以上,我设置变量 var item,underlyingArray = self.list(); – comfreakph

+0

其他问题呢...它可能会影响答案 –

回答

2

使用计算观察到的

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 
}); 
+1

如果你不得不奢求ES5,我建议使用map/reduce来代替外部总变量loop“return underlyingArray()。map(〜selectorFn〜).reduce(function(prev,curr){return prev + curr ;},0) –