【问题标题】:Populate JSON values in multiple tables With Knockout JS使用 Knockout JS 在多个表中填充 JSON 值
【发布时间】:2013-01-11 05:08:54
【问题描述】:

我有一个引导手风琴,它从 JSON 获取它的标题信息,在每个手风琴窗格中我都有一个表格,并且每个表格的信息也填充了 JSON。

我遇到的问题是所有表格数据都填充在第一个手风琴窗格中。 它不会移动到辅助表并在那里填充信息,我的 JSON 数据确实包含 ID,因此可以在项目之间导航,但不确定如何。

以下是部分代码:

<div class="well">


  </div>
  <div data-bind="attr: {id: 'collapse'+$index()}" class="accordion-body collapse">
    <div class="accordion-inner">
      <div id="injectbody">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ContentID</th>
              <th>Content</th>
              <th>Qty To Assign</th>
            </tr>
          </thead>
          <tbody data-bind="foreach: Locations">
            <tr>
              <td id="Lot" data-bind="text: ContentID"></td>
              <td id="Area" data-bind="text: Content"></td>
              <td id="QtyToAssign">
                <input type="text" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

以及让这一切正常工作的 JQuery:

   var data = {
  "d": [{
    "__type": "Sample",
      "ItemID": "1",
    "ItemName": "First Item",
      "QtyUnassigned": 10
  }, {
    "__type": "Sample",
      "ItemID": "2",
    "ItemName": "Second Item",
      "QtyUnassigned": 15
  }]
};

var data2 = {
  "d": [{
    "__type": "Sample2",
      "ItemID": 1,
      "ContentID": "1",
      "Content": "This Is The First Item Content"
  }, {
    "__type": "Sample2",
      "ItemID": 2,
      "ContentID": "2",
      "Content": "This Is The Second Item Content"
  }]
};

var ProductViewmodel;
//debugger; 

//Binds ViewModel
function bindProductModel(Products) {
  var self = this;
  self.items = ko.mapping.fromJS([]);
  ProductViewmodel = ko.mapping.fromJS(Products.d, self.items);
  console.log(ProductViewmodel());
}

//Binds First DataSet
function bindModel(vm, data) {
  var self = this;
  vm.Locations = ko.mapping.fromJS(data.d);
  console.log(ProductViewmodel());
}

//Starting Function
$(document).ready(function () {
  bindProductModel(data);
  bindModel(ProductViewmodel()[0], data2);
  ko.applyBindings(ProductViewmodel);
});

我还创建了这个Fiddle 来展示我想要达到的目标。

【问题讨论】:

    标签: json knockout.js


    【解决方案1】:

    您的错误是,由于您的 ViewModel 实际上是一个数组,因此您在这里仅将 Locations 绑定到变量 ProductViewmodel 的第一个元素。

    bindModel(ProductViewmodel()[0], data2);
    

    这意味着你有类似...

    [0].Locations = [],
    [1].Locations = undefined
    

    因此在绑定您的标记时会引发错误(请参阅小提琴中的控制台)。

    在相关说明中,您的变量命名极具误导性。 ProductViewmodel 是一个数组,但您将其命名为 ViewModel,而您将其命名为 applyBindings

    我建议您给Learn KnockoutJS 一个评论。另外,当变量命名选择camelCase,或underscore_case,或PascalCase或其他东西时,请遵守约定,但不要混合它们。最后,如果您的功能只适用于特定对象,请尝试使用 bindModel 以外的更好名称,例如 bindLocationsToModel

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 2015-11-19
      • 2016-07-01
      • 2017-10-23
      • 2014-05-18
      • 2020-09-23
      • 2013-01-15
      • 1970-01-01
      • 2018-10-24
      相关资源
      最近更新 更多