KnockOut Observable链接到JSON数据

时间:2012-08-27 09:05:43

标签: jquery knockout.js

我正在使用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 保存可用房间的类型 - 例如。单,双 - 和 TypeCount ,保存可用空间的数量。

使用KnockOut以及该论坛的大量帮助,当前的JSFiddle代码创建了一个Cart类型示例 - 您可以在其中添加房间,并选择您想要的房间类型。

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

保持总计的总和 - 因此它知道在屏幕上选择了什么,并且可以将其与JSON中的 TypeCount 相关联,用于每个 TypeName 。< / p>

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

我在JSFiddle中创建了很多分支,但是无法让它按照我的意愿去做 - 最后一个工作的例子是:Link to JSFiddle example

感谢您提供任何指示/帮助,

标记

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

1 个答案:

答案 0 :(得分:0)

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

首先,在对象中存储房间数。

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用于视图模型,而不是逻辑。