Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build table with checkboxes and bind to data using Knockout.js

I've quite (very!) new to Knockout and am hoping you can point me in the right direction with regards to the the following problem.

I've got an example of the end result I'm looking for on jsFiddle

Ultimately, I want to have a number of checkboxes in a table row which is bound to a price (which will be dynamically loaded). The final cell in the row will hold the average value of all of the prices that have been selected (where the checkbox has been checked).

This is as far as I've gotten with the ViewModel:

//--Page ViewModel

//--Set the structure for the basic price object
function Price(quote) {
  this.quote = ko.observable(quote);
}

//--Sets the structure for the contract month object
//--This includes the month, and array of Price and an average
function ContractMonthPrices(month, prices) {
  this.month = month;
  this.prices = $.map(prices, function(quote) { return new Price(quote); });

  this.average = ko.computed(function() {
      var total = 0;
      for(var i = 0; i < this.prices.length; i++)
        total += this.prices[i].quote();
      return total;
  }, this);
}

I know that's probably useless but any help would be greatly appreciated!

Thanks!

like image 983
donpisci Avatar asked May 15 '26 12:05

donpisci


1 Answers

I've slightly modified your fiddle assuming that your source data looks like that:

var allPrices = [
    { month: 'January', prices: [ 3, 4, 4, 4 ] },
    { month: 'February', prices: [ 7, 8, 2, 3 ] },
    { month: 'March', prices: [ 7, 8, 2, 1 ] }
];

http://jsfiddle.net/2Ccvk/5/

I've totally rewritten your markup with complete data-binding.

To get average computed observable working I've added the selected prop to every of your price:

function Price(quote) {
    this.quote = ko.observable(quote);
    this.selected = ko.observable(true); // bound to checkbox in markup
}

Also numerous changes and fixes were made across your code.

P.S. I've changed $.map to ko.utils.map since KO has own methods for performing common array operations. You may safely continue to use jQuery methods if you want.

like image 94
Rango Avatar answered May 18 '26 00:05

Rango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!