Wenzhixin bootstrap-table打破了Knockout.js绑定

时间:2016-05-11 16:08:10

标签: jquery twitter-bootstrap knockout.js bootstrap-table

我试图将Bootstrap Table extension集成到我的应用程序中。它通常运作良好,但我遇到了关于打破我的淘汰赛观察点的问题。

此代码available on JSFiddle说明了此问题。当为表调用bootstrapTable()时,对文本框的绑定将被破坏。如果你注释掉最后一行,那么一切都很好。

的Javascript

var order = {
  Id: 1,
  CustomerName: 'A Customer',
  Lines: [{
    ProductCode: 'Prod_1',
    Cost: 11.11,
    Qty: 1
  }, {
    ProductCode: 'Prod_2',
    Cost: 22.22,
    Qty: 2
  }, {
    ProductCode: 'Prod_3',
    Cost: 33.33,
    Qty: 3
  }, ]
};

var orderMapping = {
  'Lines': {
    create: function(options) {
      return new orderLineViewModel(options.data);
    }
  }
}

var orderLineViewModel = function(data) {
  var self = this;
if (data != null) {
  ko.mapping.fromJS(data, {}, this);
}
  self.LineValue = ko.computed(function() {
    return (self.Cost() * self.Qty()).toFixed(2);
  });
};

var orderViewModel = function(data) {
  var self = this;
  ko.mapping.fromJS(data, orderMapping, this);
};

var viewModel = new orderViewModel(order);
ko.applyBindings(viewModel);

//Removing the line below results in ko working fine
$('#OrderTable').bootstrapTable({});

HTML

<table id="OrderTable" class="table">
  <thead>
    <tr>
      <th>Product</th>
      <th>Line Value</th>
      <th>Cost</th>
      <th>Qty</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: Lines">
    <tr>
      <td><span data-bind="text: ProductCode"></span></td>
      <td><span data-bind="text: LineValue"></span></td>
      <td><span data-bind="text: Cost"></span></td>
      <td>
        <input type="text" data-bind="value: Qty" />
      </td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:0)

我看到的唯一问题是,当您更新数量时,它会更新所有项目的行值吗?

可以非常简单地解决(添加2dp格式化):

var orderLineViewModel = function(data) {
   var self = this;

   if (data != null) {
      ko.mapping.fromJS(data, {}, this);
   }

   self.LineValue = ko.computed(function() {
      return (self.Cost() * self.Qty()).toFixed(2);
   });
};

Update to Your JSFiddle

答案 1 :(得分:0)

简单修复是你需要在applyBindings之前调用bootstrapTable, $(&#34; #selector&#34;)BoostrapTable({}) - &gt;重新创建你的HTML,你就会失去敲门声。

var orderViewModel = function(data) {
  var self = this;
  ko.mapping.fromJS(data, orderMapping, this);
};

$('#OrderTable').bootstrapTable({});

var viewModel = new orderViewModel(order);
ko.applyBindings(viewModel);