var cartList = (@Html.Raw(@ViewData["json"])); //接收后台json数据
for(var item in cartList)
{
var p=cartList[item].Price;
var c=cartList[item].Count;
cartList[item].Price=ko.observable(p); //添加监控
cartList[item].Count=ko.observable(c); //添加监控
cartList[item].ComputePrice=ko.computed(function(index){ //为json添加计算价格方法
return {
read:function(){
var self = cartList[index];
return formatPrice(self.Price()* self.Count());
},owner:this
}
}(item));
cartList[item].subtract=ko.computed(function(index){ //因为要遍历整个Json数据,每个item方法需要采用闭包形式封装
return {
read:function(){
var self=cartList[index];
return self.Count();
},
write:function(){
var self=cartList[index];
if (self.Count()>1)
{
self.Count(self.Count()-1);
}
},owner:this
}
}(item));
cartList[item].add=ko.computed(function(index){
return {
read:function(){
var self=cartList[index];
return self.Count();
},
write:function(){
var self=cartList[index];
if (self.Count()<999)
{
self.Count(self.Count()+1);
}
},owner:this
}
}(item));
}