KnockoutJS-可观察对象的可观察数组 [英] KnockoutJS - Observable Array of Observable objects
问题描述
我想显示一个项目的可编辑列表,其中每个项目都是可编辑的(某种程度上类似于可编辑的网格).我正在使用KnockoutJS.我不能仅使用一个简单的Observable Array,因为正如文档所述:"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不会将视图模型的属性映射为可观察对象,这就是为什么看不到它们动态更新的原因.
ko.utils.arrayMap doesn't map your viewmodel's properties as observables, and that's why you don't see them updated dynamically.
如果您将CategoryId定义为可观察的,则会看到它按预期更新:
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屋!