0

我正在使用 KnockOutJS - 我有一个基本的 JSON 模型:

([{
    "occ": [{"name": "1 Room only","price": 53.9},
            {"name": "1 B&B","price": 62.16},],
    "TypeName": "Single",
    "TypeID": "3121",
    "TypeCount": "5"
   },
{
    "occ": [{"name": "2 B&B","price": 24.23},
            {"name": "2 DBB","price": 32.95}],
    "TypeName": "Double",
    "TypeID": "4056",
    "TypeCount": "4"
   }])

这个想法是,TypeName保存可用房间的类型 - 例如。Single、Double - 和TypeCount保存了可用房间的数量。

使用 KnockOut 以及来自这个论坛的大量帮助,当前的 JSFiddle 代码创建了一个购物车类型示例 - 您可以在其中添加房间,并选择您想要的那种类型的房间的数量。

但是,如果用户选择“ Single ”,并从数量中选择4(意味着只剩下1 个 Single Room),然后单击 Add Room,然后再次选择TypeName “Single”,我希望 KnockOut 能够已经跟踪选择了“ Single ”的先前行以及选择的数量 - 因此知道用户在再次添加单人房间时只能从数量中选择1

有点保持运行总计 - 所以它知道在屏幕上选择了什么,并且可以将其与 JSON 中的每个TypeName的TypeCount相关联。

这类似于 KnockOuts 网站上的自定义绑定教程:KnockOut Custom Bindings Example

我在 JSFiddle 中创建了许多分支,但无法让它做我想做的事 - 最后一个工作示例是:链接到 JSFiddle 示例

感谢您的任何指示/帮助,

标记

HTML是

<div class='liveExample'> 

<table width='100%' border="1">
    <thead>
        <tr>
            <th width='25%'>Room Type</th>
                <th width='25%'>Occ</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: $root.RoomCategories, optionsText: "TypeName", optionsCaption: "Select...", value: category'> </select>
            </td>
            <td data-bind="with: category">
                <select data-bind='options: occ, 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' data-bind="with: category">
                <select data-bind="visible: $parent.product, options: ko.utils.range(0, TypeCount), value: $parent.quantity"></select>
            </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>
<p class='grandTotal'>
    Total value: <span data-bind='text: formatCurrency(grandTotal())'> </span>
</p>
<button data-bind='click: addLine'>Add room</button>
<button data-bind='click: save'>Submit booking</button>

并且 KnockOut 代码是

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

var CartLine = function() {
var self = this;
self.category = ko.observable();
self.categoryID = 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.RoomCategories = ko.observableArray([]);
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()
    })
    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() ? {
            category: line.category().TypeName,
            categoryID: line.category().TypeID,
            productName: line.product().name,
            quantity: line.quantity()
        } : undefined
    });
    alert("Could now send this to server: " + JSON.stringify(dataToSave));
    };
};

var cart = new Cart();

ko.applyBindings(cart);

//simulate AJAX
setTimeout(function() {
cart.RoomCategories([{
    "occ": [{
        "name": "1 Room only",
        "price": 53.9},
    {
        "name": "1 B&B",
        "price": 62.16}, ],
    "TypeName": "Single",
    "TypeID": "3121",
    "TypeCount": "2"


    },
{
    "occ": [{
        "name": "2 B&B",
        "price": 24.23},
    {
        "name": "2 DBB",
        "price": 32.95}],
    "TypeName": "Double",
    "TypeID": "4056",
    "TypeCount": "2"


    },
{
    "occ": [{
        "name": "2+1 BB",
        "price": 34.25},
    {
        "name": "2+1 DBB",
        "price": 36.23}],
    "TypeName": "Family",
    "TypeID": "5654",
    "TypeCount": "4"}]);
}, 100);
4

1 回答 1

0

本质上,当您应该通过将运行总计存储在 JS 对象中并使用 JS 运行计算来使用本机 javascript 时,您要求淘汰赛做太多的逻辑工作。我将给出的示例不是即插即用您的代码,但它是相关的。

首先,将房间计数存储在一个对象中。

roomcount = { // object can be accessed by any other variable in your app
    single: 5, // data from json or where ever
    double: 4
}

然后,您的 KO 视图模型将像这样工作

self.showAvailableSingle = ko.ovservable(roomcount.single) // Show available rooms to user
self.showAvailableDouble = ko.ovservable(roomcount.double)
self.selectSingleQuantity = ko.observable(""); // user input number of rooms
self.selectDoubleQuantity = ko.observable("");

self.selectSingleQuantity = function() { // click event
    roomcount.single = roomcount.single - self.selectSingleQuantity();
    self.showAvailableSingle(roomcount.single); // this will update what is shown to the user
}

self.selectDoubleQuantity = function() { // click event
    roomcount.Double = roomcount.Double - self.selectDoubleQuantity();
    self.showAvailableDouble(roomcount.Double);
}

就像我说的,这需要修改以使用您的代码,但希望它是一个示例,可以让您走上正确的道路。这个总体思路可用于更新选择输入选项或其他更高级的东西。

您希望在应用程序的计算和逻辑方面尽可能少地使用 KO 的另一个原因是,您的最终 KO 视图模型将很大并且很烦人,无法解析您的必要数据。尝试仅将 KO 用于视图模型而不是逻辑,这一点很重要。

于 2012-08-27T15:27:51.317 回答