2014-03-04 63 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) –