【问题标题】:jQuery and KnockOutJS linking a slider to the Cart examplejQuery 和 KnockOutJS 将滑块链接到购物车示例
【发布时间】:2013-09-16 10:50:17
【问题描述】:

使用来自 KnockOutJS.com 的购物车示例 - 您将如何链接滑块(或滑块数量),以便总价值考虑到下拉列表和附加项目的数量(这里的太阳镜大小写)在 Slider 控件中选择。

我得到了调用 getExtrasTotal() 函数的总值 - 当下拉列表或项目数量发生变化时 - 但在滑块发生变化时没有。

这里有一个小提琴:http://jsfiddle.net/mtait/mBxky/1/

HTML:

<div class='liveExample'> 

<table width='100%'>
    <thead>
        <tr>
            <th width='25%'>Category</th>
            <th width='25%'>Product</th>
            <th class='price' width='15%'>Price</th>
            <th class='quantity' width='10%'>Quantity</th>
            <th class='price' width='15%'>Subtotal</th>
            <th width='10%'> </th>
        </tr>
    </thead>
    <tbody data-bind='foreach: lines'>
        <tr>
            <td>
                <select data-bind='options: sampleProductCategories, optionsText: "name", optionsCaption: "Select...", value: category'> </select>
            </td>
            <td data-bind="with: category">
                <select data-bind='options: products, optionsText: "name", optionsCaption: "Select...", value: $parent.product'> </select>
            </td>
            <td class='price' data-bind='with: product'>
                <span data-bind='text: formatCurrency(price)'> </span>
            </td>
            <td class='quantity'>
                <input data-bind='visible: product, value: quantity, valueUpdate: "afterkeydown"' />
            </td>
            <td class='price'>
                <span data-bind='visible: product, text: formatCurrency(subtotal())' > </span>
            </td>
            <td>
                <a href='#' data-bind='click: $parent.removeLine'>Remove</a>
            </td>
        </tr>
    </tbody>
</table>
<br />
<label for="slider1">Sunglasses $20 each - how many would you like</label>
<input type="range" class="slide" name="slider1" id="slider1" min="0" max="10" value="0" data-price="20.00" data-id="1">
<br />
<label for="slider2">Doc holder $15 each - how many would you like</label>
<input type="range" class="slide" name="slider2" id="slider2" min="0" max="10" value="0" data-price="15.00" data-id="2">


<p class='grandTotal'>
    Total value: <span data-bind='text: formatCurrency(grandTotal())'> </span>
</p>
<button data-bind='click: addLine'>Add product</button>
<button data-bind='click: save'>Submit order</button>

</div>

Javascript:

function formatCurrency(value) {
return "$" + value.toFixed(2);
}

var CartLine = function() {
var self = this;
self.category = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function() {
    return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});

// Whenever the category changes, reset the product selection
self.category.subscribe(function() {
    self.product(undefined);
});
};

var Cart = function() {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function() {
    var total = 0;
    $.each(self.lines(), function() { total += this.subtotal() })
    var 
    return total;
});

// Operations
self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };
self.save = function() {
    var dataToSave = $.map(self.lines(), function(line) {
        return line.product() ? {
            productName: line.product().name,
            quantity: line.quantity()
        } : undefined
    });
    alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};

function getExtrasTotal() {
var extrastotal = 0;
var count = 0;
var arr = [];
$('.slide')
     .each(function (index, Element) {
         var obj = {
             id: $(Element).data("id"),
             price: $(Element).data("price"),
             number: $(Element)
                 .val()
         };
         extrastotal += obj.number * obj.price;
     });
return extrastotal;
}

ko.applyBindings(new Cart());

谢谢,

标记

【问题讨论】:

    标签: javascript jquery jquery-mobile knockout.js


    【解决方案1】:

    首先,您需要确保滑块也更新ko.observable

    然后,extrasTotal 也需要像grandTotal 一样是ko.computed,但要观察额外内容而不是购物车线。

    I updated your fiddle 有一些快速和肮脏的:

    <input type="range" class="slide" name="slider1" id="slider1" min="0" max="10" data-bind="value: sunglasses">
    

    self.extrasTotal = ko.computed(function() {
        var sunglasses = self.sunglasses(); 
        var docholders = self.docholders(); 
        return sunglasses * self.sunglassPrice + docholders * self.docholderPrice; 
    }); 
    

    当然,实际上您可能希望将其制成一系列可能的附加功能,并使用foreach 渲染&lt;input&gt;:s,并从数据库中获取价格。

    This fiddle hints on how to do that

    self.extrasTotal = ko.computed(function() {
        var total = 0; 
        ko.utils.arrayForEach(self.extras(), function (extra) {
            var count = extra.count(); 
            total = total + (count * extra.price); 
        });
        return total; 
    }); 
    

    【讨论】:

    • 谢谢@dan-p - 一个更优雅的解决方案!干杯,马克
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多