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を選択し (つまり、 Single Roomが 1 つしか残っていないことを意味します)、[Add Room] をクリックし、再度TypeName「Single」を選択した場合、KnockOut ができるようにしたいと思います。 「シングル」が選択された前の行と選択された数量を追跡しているため、シングルルームを再度追加するときに、ユーザーが数量から1つしか選択できないことがわかります。

現在の合計を維持するようなもの - 画面で何が選択されているかを認識し、それを各TypeNameの JSON の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>

ノックアウトコードは

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 をできるだけ使用したくないもう 1 つの理由は、最終的な KO ビュー モデルが大きくなり、必要なデータを解析するのが面倒になるためです。KO は、ロジックではなく、ビュー モデルに対してのみ使用することが重要です。

于 2012-08-27T15:27:51.317 に答える