【问题标题】:Build table with checkboxes and bind to data using Knockout.js使用复选框构建表格并使用 Knockout.js 绑定到数据
【发布时间】:2013-05-17 01:23:34
【问题描述】:

我对 Knockout 非常(非常!)新手,希望您能就以下问题为我指明正确的方向。

我有一个我在 jsFiddle 上寻找的最终结果示例

最终,我希望在绑定到价格(将动态加载)的表格行中有多个复选框。行中的最后一个单元格将保存所有已选择价格的平均值(复选框已选中)。

这是我对 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);
}

我知道这可能没用,但我们将不胜感激!

谢谢!

【问题讨论】:

  • 好的,但是你的问题是什么?什么不工作?
  • 暂时没有!我无法理解如何绑定复选框,因为我读过的所有内容都显示了一个复选框“列表”而不是表格。

标签: javascript html knockout.js


【解决方案1】:

假设你的源数据看起来像这样,我稍微修改了你的小提琴:

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/

我已经用完整的数据绑定完全重写了你的标记。

为了让 average 计算出可观察的工作,我已将 selected 属性添加到您的每个价格中:

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

还对您的代码进行了许多更改和修复。

附注我已将$.map 更改为ko.utils.map,因为KO 有自己的方法来执行常见的数组操作。如果你愿意,你可以安全地继续使用 jQuery 方法。

【讨论】:

  • 谢谢伙计——这真是一种享受!我总是发现,虽然 Knockout 网站上的示例有所帮助,但当我尝试申请我的“现实世界”工作时,我不知道从哪里开始!
猜你喜欢
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2020-10-01
  • 2013-01-14
  • 2012-07-14
  • 1970-01-01
相关资源
最近更新 更多