如何更新购物车总价中的值

How to update value in cart total price?

本文关键字:购物车 何更新 更新      更新时间:2023-09-26

我正在使用jQuery Mobile设计购物车移动应用程序。我正在使用单页架构在页面之间进行导航。每个页面的标题中都有一个 CART 图标,其中显示了购物篮的当前总价。我使用了KnockoutJS,在每个页面的顶部,我都显示购物车总价为:

<a href="#cartBox" data-icon="myapp-settings" data-theme="b" data-role="button"><span data-bind="text: price"></span>  </a>

我在每个页眉部分使用的上述行。

这是我用来在任何地方显示价格值的脚本:

function cartPrice() {
    this.price = ko.observable(0.00);
}
ko.applyBindings(new cartPrice());

到处都有产品的列表视图,现在我希望每当用户单击列表视图项目时,价格都会更新为一个值,该值在隐藏在特定 li 中的输入类型中给出,并且该值在价格当前值中增加。

我该怎么做?

您应该在一个

根视图模型中聚合列表视图的CartPrice和视图模型。 例如像这样:

function CartPrice() {
  this.price = ko.observable(0.00);
}
function ListViewModel() {
  var self = this, i = 1;
  
  self.items = ko.observableArray([]);
  
  self.addItem = function() {
    self.items.push({
      name: "New item " + (++i),
      price: +(Math.random() * 2.5 + 1.0).toFixed(2)
    });
  }
}
function RootViewModel() {
  var self = this;
  
  self.cartPriceVm = new CartPrice();
  self.listVm = new ListViewModel();
  
  self.listVm.items.subscribe(function() {
    var newTotal = self.listVm.items().reduce(function(a,b) { return a + b.price; }, 0);
    //console.log(newTotal);
    self.cartPriceVm.price(newTotal);
  });
}
var vm = new RootViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko with: cartPriceVm -->
Total price: $<strong data-bind="text: price"></strong>.
<!-- /ko -->
<!-- ko with: listVm -->
<ul data-bind="foreach: items">
  <li>
    <span data-bind="text: name"></span> -
    $<span data-bind="text: price"></span>
  </li>
</ul>
<button data-bind="click: addItem">Add Item</button>
<!-- /ko -->