【发布时间】:2015-12-08 18:18:01
【问题描述】:
我正在尝试使用 knockoutjs 实现购物车。
我的问题是,每当用户导航到网站的其他页面时,购物车中的数据(使用 observableArray 创建)不会保留。
我想要的是当用户仍然导航到不同的类别时,他/她应该能够查看在前一个类别中排序的数据。
我的 HTML 文件:
<div class="orderSegement" data-bind="visible: viewOrderTab()">
<section>
<h2 class="hidden">Order</h2>
<article class="OrderedItems">
<div class="headindOrder headindOrderLeft0">Name</div><div class="headindOrder headindOrderLeft25">Price</div><div class="headindOrder headindOrderLeft50">Qty</div>
<div data-bind="foreach: orderList">
<div class="OrderData" data-bind="visible: ProductQty">
<label data-bind="text: ProductName"></label>
<label data-bind="text: ProductPrice"></label>
<label data-bind="text: ProductQty"></label>
<a href="#" data-bind="click: $root.removeFromList">Remove</a>
</div>
</div>
<label data-bind="visible: totalPrice, text: totalPrice"></label>
<button class="button" data-bind="click: viewOrder">Hide</button>
<button class="button" data-bind="visible: totalPrice, click: submitToServer">Order</button>
</article>
</section>
</div>
我的视图模型文件
self.orderList = ko.observableArray(null, {persist: 'orderList'});
我试图通过 knockout.localStorage.js 实现这一目标。 但是我无法成功实施它。 knockout.localStorage.js 是否仅适用于 ko.observable() 变量? 或者它是否支持 ko.observableArray 或 ko.computed,如果支持,那么如何?
【问题讨论】:
-
“您可以让 ko.observable 或 ko.observableArray 自动将其值保存到 localStorage”documentation 中说。所以它应该在可观察数组上工作。您能否更具体地说明什么不起作用。
-
使用此代码我正在填充我的 orderList。 self.addToCart = function (item, event) { /*获取当前项目索引*/ /*在 dom 元素中 $index() 就足够了,但是在 viewModel 中要获取上下文*/ var context = ko.contextFor(event.目标); var index = context.$index(); var incQty = self.prodList()[index].ProductQty();公司数量++; self.prodList()[index].ProductQty(incQty); self.orderList.push(new ProdList(self.prodList()[index])); };但是,当用户导航到网站中的任何其他页面时,“orderList”中的项目不会保留。
-
用户之前选择的所有项目都从“orderList”中消失,我留下了空白的 orderList。希望这可以帮助。抱歉,我不知道如何在 cmets 中格式化代码。
标签: javascript jquery knockout.js knockout-mapping-plugin