在嵌套的动态observableArray中查看数据绑定

时间:2017-10-18 06:54:40

标签: javascript knockout.js

我需要在observableArray中添加动态大小的observableArray并将数据绑定到View。

当我在View中编辑时,视图是来自newData的渲染值,但不会在newData中更新它。



ko.applyBindings(new (function () {
  var self = this;
  self.lengthNewData  = ko.observable(2);
  self.newData  = ko.observableArray();

  self.AddDataStrings = function () {
    let newString = ko.observableArray();
    for(let i0 = 0; i0 < self.lengthNewData(); i0++)
      newString.push(i0);
    self.newData.push(newString);
  }

  self.SendData = function () {
    alert(ko.toJSON(self.newData));
  }
})());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<span data-bind="visible: !newData().length">Number of rows: <input data-bind="value: lengthNewData"/></span>
<input type="button" value="Add" data-bind="click: $root.AddDataStrings"/>
<input type="button" value="Send"  data-bind="visible: newData().length, click: $root.SendData"/><br>

<table>
  <tbody data-bind="foreach: newData">
    <tr data-bind="foreach: $data">
      <td><input data-bind="value: $data"/></td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

https://jsfiddle.net/tvxyyzkp/6/

推送Add,对其进行修改并按Send。数据未被修改!
为什么和需要改变什么?

1 个答案:

答案 0 :(得分:2)

您的代码中存在两个直接错误。

  1. 您不会将观察值推送到newString。你应该这样做:

    newString.push(ko.observable(i0));
    
  2. 您将输入绑定到$data$data包含 unwrapped 数据值,即它不可观察。在这样的设置中绑定到$rawData

  3. 这有效:

    &#13;
    &#13;
    ko.applyBindings(new(function() {
      var self = this;
    
      self.lengthNewData = ko.observable(2);
      self.newData = ko.observableArray();
    
      self.AddDataStrings = function() {
        let newString = ko.observableArray();
        for (let i0 = 0; i0 < self.lengthNewData(); i0++)
          newString.push(ko.observable(i0));
        self.newData.push(newString);
      }
    
      self.SendData = function() {
        alert(ko.toJSON(self.newData));
      }
    })());
    &#13;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    <span data-bind="visible: !newData().length">Number of rows: <input data-bind="value: lengthNewData"/></span>
    <input type="button" value="Add" data-bind="click: AddDataStrings" />
    <input type="button" value="Send" data-bind="visible: newData().length, click: SendData" /><br>
    
    <table>
      <tbody data-bind="foreach: newData">
        <tr data-bind="foreach: $data">
          <td><input data-bind="value: $rawData" /></td>
        </tr>
      </tbody>
    </table>
    
    
    <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
    &#13;
    &#13;
    &#13;