如何在更改数量时自动更新grandtotal

时间:2016-03-23 18:19:51

标签: javascript knockout.js

我正在使用淘汰赛购买我的购物车,我似乎无法根据物品的变化自动更新总计。

查看

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

我是淘汰赛的新手,但这里有什么问题吗?

1 个答案:

答案 0 :(得分:2)

所以问题是你只是更新arrayFromJson这不是淘汰赛所知道的东西,所以它不知道需要更新你的{{1}计算。并非所有代码都显示,所以我不确定所有函数和实例的范围,但基本上你只需要告诉knockout重新计算grandTotal,理想情况下你会从{{1功能:

grandTotal

请注意此处的UpdateCookiefunction 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()这里(再次)。这将使用新的observable替换原始的observable,并放弃arrayPushAll() s对原始实例的所有订阅。

一旦完成,然后更新您的计算机以依赖myAppViewModel.cartItems = ko.observableArray(arrayFromJson);,因为它 可观察,因此knockout将检测对其的更改,然后自动为您重新计算值。

computed