KnockoutJS - 可观察对象的可观察数组 [英] KnockoutJS - Observable Array of Observable objects
问题描述
我想显示一个可编辑的项目列表,其中的每个项目都是可编辑的(某种程度上类似于可编辑的网格).我正在使用 KnockoutJS.我不能只使用一个简单的 Observable 数组,因为正如文档所述一个 observableArray 跟踪数组中的哪些对象,而不是这些对象的状态"
I would like to display an editable list of items, each item of which is editable (kind of like an editable grid, in a way). I am using KnockoutJS. I cannot use just a simple Observable Array because, as the documentation states "An observableArray tracks which objects are in the array, not the state of those objects"
因此,我创建了一个可观察对象的 observableArray(使用 utils.arrayMap),并将它们绑定到视图.但是,问题是如果我在屏幕上编辑数据,用户在屏幕上所做的任何数据输入更改似乎都不会生效.请参阅 http://jsfiddle.net/AndyThomas/E7xPM/
So, I have created an observableArray of observable objects (using utils.arrayMap), and bound them to the view. However, the problem is that if I edit the data on screen, any data-entry changes that the user makes on screen do not appear to take effect. See http://jsfiddle.net/AndyThomas/E7xPM/
我做错了什么?
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js" type="text/javascript"></script>
<table>
<tbody data-bind="template: { name:'productListJavascriptTemplate', foreach: products}">
</tbody>
</table>
<script type="text/html" id="productListJavascriptTemplate">
<tr>
<td>Name: <input data-bind="value: Name"/></td>
<td>Name: <span data-bind="text: Name"/></td>
<td><select data-bind="options: this.viewModel.categories,
optionsText: 'Name', optionsValue: 'Id', value: CategoryId,
optionsCaption: 'Please select...'"></select></td>
<td>CategoryId: <input data-bind="value: CategoryId"/></td>
</tr>
</script>
var categoryList= [
{
Name: "Electronics",
Id: "1"},
{
Name: "Groceries",
Id: "2"}
];
var initialData= [
{
Name: "Television",
CategoryId: "1"},
{
Name: "Melon",
CategoryId: "2"}
];
var viewModel = {
products: ko.observableArray(
ko.utils.arrayMap(initialData, function(product) {
return ko.observable(product);
})),
categories: ko.observableArray(categoryList)
};
$(function() {
ko.applyBindings(viewModel);
});
推荐答案
ko.utils.arrayMap 不会将视图模型的属性映射为 observable,这就是为什么您看不到它们动态更新的原因.
ko.utils.arrayMap doesn't map your viewmodel's properties as observables, and that's why you don't see them updated dynamically.
如果您将 CategoryId 定义为 observable,您会看到它按预期更新:
If you define your CategoryId as an observable, you'll see it update as expected:
var initialData = [
{
Name: "Television",
CategoryId: ko.observable("1")
},
{
Name: "Melon",
CategoryId: ko.observable("2")
}
];
查看更新的 jsfiddle:http://jsfiddle.net/tuando/E7xPM/5/
See this updated jsfiddle: http://jsfiddle.net/tuando/E7xPM/5/
这篇关于KnockoutJS - 可观察对象的可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!