双向数据绑定不适用于knockout ObservableArrays

问题描述 投票:0回答:1

我有以下代码,它有两个功能。

  1. 单击“添加更多”,将新值推送到可观察数组,将新文本框添加到UI
  2. 单击“保存”将显示div上文本框中的值。

var model = function() {
  var self = this;
  self.inventoryItems = ko.observableArray();

  myArray = ["Value1", "V1lue2", "Value3", "Value4"];
  self.inventoryItems(myArray);

  self.addItems = function(vm) {
    self.inventoryItems.push('New Item');
  }

  self.SaveInventory = function(data) {
    $('#htmlBlock').html(myArray);
    console.log(myArray)
  };

};

ko.applyBindings(new model());
ul {
  list-style: none;
}

li {
  margin-top: 5px;
}

.info-text,
a,
button {
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul data-bind="foreach: inventoryItems">
  <li>
    <input data-bind="value: $data" />
  </li>
</ul>
<div>
  <a data-bind="click: addItems">+ Add more</a>
</div>
<button type="submit" class="btn btn-accent" data-bind="click: SaveInventory">Save changes</button>
<div class='info-text' id="htmlBlock">
</div>

使用此代码,我的UI初始化正常,当我点击“添加更多”时,能够获得一个新的文本框,myArray / inventoryItems也正常工作。

但是,如果我编辑任何项目并保存该值,我将无法获得更新值。

我错过了什么?

javascript html mvvm data-binding knockout.js
1个回答
2
投票

不需要对可观察数组中的底层数组进行单独引用,它只会使事情混淆。使用self.inventoryItems()读出值。

实时查看模型外观的好方法是使用data-bind="text: ko.toJSON($data, null, '\t')"元素

为了进行双向绑定,您需要使每个值(对于输入字段)都是可观察的。通常我会为此使用单独的构造函数。

function EditableField(initialValue) {
  // each value you want to be able to have a two-way binding for needs to be observable
  this.value = ko.observable(initialValue);
}

var model = function() {
  var self = this;
  self.inventoryItems = ko.observableArray(["Value1", "V1lue2", "Value3", "Value4"].map(function(item) {
    // run each array value through constructor
    return new EditableField(item);
  }));

  self.addItems = function(vm) {
    self.inventoryItems.push(new EditableField('New Item'));
  }

  self.SaveInventory = function(data) {
    console.log(ko.toJS(self.inventoryItems)); // fetch the updated array
  };

};

ko.applyBindings(new model());
ul {
  list-style: none;
}
li {
  margin-top: 5px;
}
.info-text,
a,
button {
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul data-bind="foreach: inventoryItems">
  <li>
    <!-- use textInput binding for live updates, bound to the value property from constructor -->
    <input data-bind="textInput: value" />
  </li>
</ul>
<div>
  <a data-bind="click: addItems">+ Add more</a>
</div>
<button type="submit" class="btn btn-accent" data-bind="click: SaveInventory">Save changes</button>

<!-- display the model in real time -->
<pre class='info-text' data-bind="text: ko.toJSON($data, null, '\t')">
</pre>
© www.soinside.com 2019 - 2024. All rights reserved.