Javascript 如何在数量更改时自动更新总计

Javascript 如何在数量更改时自动更新总计,javascript,knockout.js,Javascript,Knockout.js,我正在为我的购物车使用knockout,我似乎无法根据商品的变化自动更新总计 查看 <div data-bind="foreach: cartItems"> <div class="row item-row"> <h3 data-bind="text: fullname"></h3> <p data-bind="text: sku"></p> <select data-bind="quantityDrop

我正在为我的购物车使用knockout,我似乎无法根据商品的变化自动更新总计

查看

<div data-bind="foreach: cartItems">
 <div class="row item-row">
  <h3 data-bind="text: fullname"></h3>
  <p data-bind="text: sku"></p>
  <select data-bind="quantityDropdown: number, event: {change: $parent.updateqty}"></select>
 </div>
</div>

<div class="row">
    <p class="checkout-box-totals">Subtotal:</p>
    <p class="checkout-box-price">
        <span class="glyphicon glyphicon-usd" data-bind="text: subtotal()"></span>
    </p>
</div>

<hr/>
<div class="row checkout-box-total">
    <p class="checkout-box-totals">Total:</p>
    <p class="checkout-box-price">
        <span class="glyphicon glyphicon-usd" data-bind="text: grandTotal()"></span>
    </p>

</div>

小计:


总计:

视图模型

    //This items placed in cart is placed in my cookiearray
    //cookiearray contains = datetime, id, typeid, qty, fullname, image, price, sku, weight)
    var cookiestring = $.cookie("cookieCart");
    var arrayfromJson = JSON.parse(cookiestring);

    //Deletes the cookie
    var deleteCookie = function (name) {
      document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
    };

    function UpdateCookieQty(id, typeid, select) {
       for (var i = arrayfromJson.length - 1; i >= 0; i--) {
           if (arrayfromJson[i].id === id && arrayfromJson[i].typeid === typeid) {
               arrayfromJson[i].qty = select;
           }
       }
       //recreates the cookie string after updating the quantity. This new quantity isnt read in the observable until browser is refreshed.
       deleteCookie("cookieCart");
       $.cookie("cookieCart", JSON.stringify(arrayfromJson), { path: "/" });
   }



function AppViewModel() {
    var self = this;
    self.cartItems = ko.observableArray(arrayfromJson);
    self.quantity = ko.observable(); //here im trying to make the quantity observable.
    var totalShipWeight = 0;

    //calculating total weight of the cart
    for (var n = 0; n < self.cartItems().length; n++) {
        var itemweight = parseFloat(arrayfromJson[n].weight, 10);
        var shipqty = parseFloat(arrayfromJson[n].qty, 10);
        totalShipWeight += itemweight * shipqty;
    }

    //calculating the subtotal doesn't update when quantity is changed :(
    self.subtotal = ko.computed(function () {
        var total = 0;
        for (var i = 0; i < self.cartItems().length; i++) {
            var itemPrice = parseFloat(arrayfromJson[i].price, 10);
            var itemqty = parseFloat(arrayfromJson[i].qty, 10);
            total += itemPrice * itemqty;
        }
        return total;
    });

    //calculating tax if tax applies, doesn't update when quantity is changed
    self.taxedItems = ko.pureComputed(function () {
        var taxcost = 0;
        var total = 0;
        if (totalShipWeight > 0) {
            for (var i = 0; i < self.cartItems().length; i++) {
                var itemPrice = parseFloat(arrayfromJson[i].price, 10);
                var itemqty = parseFloat(arrayfromJson[i].qty, 10);
                total += itemPrice * itemqty;
            }
            taxcost = parseFloat((total * tax).toFixed(2));
        } 
        return taxcost;
    });

    //calculating tax if tax applies, doesn't update when quantity is changed
    self.grandTotal = ko.pureComputed(function () {
        var total = 0;
        var grandTotal = 0;
        for (var i = 0; i < self.cartItems().length; i++) {
            var itemPrice = parseFloat(arrayfromJson[i].price, 10);
            var itemqty = parseInt(arrayfromJson[i].qty, 10);
            total += itemPrice * itemqty;
        }
        grandTotal = total + (total * tax);
        //Add shipping cost
        return grandTotal;
    });

    //number = 50 from controller. this is just to display dropdown for max amount of quantity
    ko.bindingHandlers.quantityDropdown = {
        update: function (element) {
            for (var i = 1; i < number + 1; i++) {
                var selectedQty = "";

                for (var x = 0; x < self.cartItems().length; x++) {
                    var itemqty = parseFloat(arrayfromJson[x].qty, 10);

                    if (i === itemqty) {
                        selectedQty = " selected='selected'";
                    }
                }
                // Add each option element to the select here
                $(element).append("<option value='" + i + "' " + selectedQty + ">" + i + "</option>");
            }
        }
    };


    //this is where the user updates quantity. I goes to the function, 
    //updates quantity for particular item (but for some reason updates both items).
    //then the change is supposed to reflect in the subtotal and grandtotal, but doesnt.
    self.updateqty = function (viewModel, event) {

        UpdateCookieQty(this.id, this.typeid, event.target.value);
        }
    }

    ko.applyBindings(new AppViewModel());
//放置在购物车中的这些项目被放置在我的cookiearray中
//cookiearray包含=日期时间、id、类型id、数量、全名、图像、价格、sku、重量)
var cookiestring=$.cookie(“cookieCart”);
var arrayfromJson=JSON.parse(cookiestring);
//删除cookie
var deleteCookie=函数(名称){
document.cookie=name+“=;expires=Thu,1970年1月1日00:00:01 GMT;”;
};
函数updateCokieQty(id、typeid、select){
对于(var i=arrayfromJson.length-1;i>=0;i--){
if(arrayfromJson[i].id==id&&arrayfromJson[i].typeid==typeid){
arrayfromJson[i].qty=select;
}
}
//在更新数量后重新创建cookie字符串。在刷新浏览器之前,不会在可观察对象中读取此新数量。
删除Cookie(“cookieCart”);
$.cookie(“cookieCart”,JSON.stringify(arrayfromJson),{path://“});
}
函数AppViewModel(){
var self=这个;
self.cartItems=ko.observearray(arrayfromJson);
self.quantity=ko.observable();//这里我试图让这个数量可以观察到。
var totalShipWeight=0;
//计算购物车的总重量
对于(var n=0;n0){
对于(var i=0;i

我对knockout还很陌生,但是这里有什么问题吗?

所以问题是你只更新了
arrayFromJson
,knockout根本不知道这件事,所以它不知道需要更新你的
grandTotal
计算值。不是所有的代码都显示出来,所以我不确定所有的范围函数和实例,但本质上您只需要告诉knockout重新计算
grandTotal
,理想情况下,您可以通过
UpdateCookie
函数:

function UpdateCookieQty(id, typeid, select) {
   for (var i = arrayfromJson.length - 1; i >= 0; i--) {
       if (arrayfromJson[i].id === id && arrayfromJson[i].typeid === typeid) {
           arrayfromJson[i].qty = select;
       }
   }
   //recreates the cookie string after updating the quantity. This new quantity isnt read in the observable until browser is refreshed.
   deleteCookie("cookieCart");
   $.cookie("cookieCart", JSON.stringify(arrayfromJson), { path: "/" });
   myAppViewModel.cartItems.removeAll();
   ko.utils.arrayPushAll(myAppViewModel.cartItems, arrayFromJson);
}
注意这里的
.removeAll()
arrayPushAll()
调用,这可以避免人们在使用敲除时犯的一个常见错误。您要确保您没有这样做:
myAppViewModel.cartItems=ko.observableArray(arrayFromJson);
这里(再次)。这将用一个新的observable替换原始observable,并放弃
计算的
s将在原始实例上拥有的所有订阅

一旦完成,然后更新您的计算值,使其依赖于可观察的
cartItems
,这样敲除将检测到该值的变化,然后自动为您重新计算值

self.grandTotal = ko.pureComputed(function () {
    var total = 0;
    var grandTotal = 0;
    for (var i = 0; i < self.cartItems().length; i++) {
        var itemPrice = parseFloat(cartItems[i].price, 10);
        var itemqty = parseInt(cartItems[i].qty, 10);
        total += itemPrice * itemqty;
    }
    grandTotal = total + (total * tax);
    //Add shipping cost
    //Discount CMEZ
    return grandTotal;
});
self.grandTotal=ko.pureComputed(函数(){
var合计=0;
var-grandTotal=0;
对于(var i=0;i