I’m using KnockOutJS – I have a basic JSON model:
([{
"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"
}])
The idea is, TypeName holds the type of room available – eg. Single, Double – and TypeCount, holds the number of that room available.
Using KnockOut, and a lot of help from this forum, the current JSFiddle code creates a Cart type example – where you can add rooms, and select how many of that type of room you would like.
However, if the user selects “Single“, and selects 4 from the quantity (meaning there is only 1 Single Room remaining), and then clicks Add Room, and again, selects TypeName “Single”, I would like KnockOut to be able to have kept a track of previous lines having “Single” chosen, and the quantity chosen – and therefore know that the user can only select 1 from the quantity, when adding a Single room again.
Sort of keeping a running total – so it knows what’s been selected on the screen, and can relate that back to the TypeCount in the JSON for each TypeName.
This is similar to the custom bindings tutorial on KnockOuts site: KnockOut Custom Bindings Example
I’ve created many forks in JSFiddle, but can’t get it to do what I want – the last working example is: Link to JSFiddle example
Thank you for any pointers/help,
Mark
The HTML is
<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>
and the KnockOut code is
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);
Essentially you’re asking knockout to do too much logical work when you should be using native javascript by storing your running total in a JS object and using JS to run the calculations. The example I’ll give isn’t plug & play into your code, but it’s relevant.
First, store room counts in an object.
Then, your KO viewmodel would work something like this
Like I said, this will need to be modified to work with your code, but hopefully it’s an example that will send you down the right path. This general idea can be used to update select input options or other fancier things.
The other reason you want to use KO as little as possible for the computational and logical aspects of your app is because your final KO view model will be large and annoying to parse your necessary data. It’s important to try and use KO only for the view model, and not logic.