javascript Knockout JS - 如何正确绑定 observableArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9510539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout JS - How to correctly bind an observableArray
提问by Sam Anthony
Please take a look at this example. http://jsfiddle.net/LdeWK/2/
请看一下这个例子。 http://jsfiddle.net/LdeWK/2/
I want to know how to bind values of an observable array. I know the problem in the example above, it is this line
我想知道如何绑定可观察数组的值。我知道上面例子中的问题,就是这一行
<p>Editing Fruit: <input data-bind="value: $data" /></p>
$data is the actual value, not the observable function that you would normally bind. This seems like it should be a pretty straight forward process, however I cant figure it out.
$data 是实际值,而不是您通常会绑定的可观察函数。这似乎应该是一个非常直接的过程,但是我无法弄清楚。
In other cases I have used observable arrays and had an observable object as each element of the observable array. I wanted to know how to get this to work with just observable array.
在其他情况下,我使用了 observable 数组,并有一个 observable 对象作为 observable 数组的每个元素。我想知道如何让它仅与可观察数组一起工作。
Thanks
谢谢
回答by RP Niemeyer
If you are binding read/write to items in an array or an observableArray, then they will need to be a property of an object. Otherwise, $data
will be the unwrapped observable and there is no way for KO to write to the actual observable.
如果您将读/写绑定到数组或 observableArray 中的项目,则它们将需要是对象的属性。否则,$data
将是解包的 observable 并且 KO 无法写入实际的 observable。
You would have to do something like:
您必须执行以下操作:
var ViewModel = function(myFruit) {
var observableFruit = ko.utils.arrayMap(myFruit, function(fruit) {
return { name: ko.observable(fruit) };
});
this.fruit = ko.observableArray(observableFruit);
};
ko.applyBindings(new ViewModel( ["Apple", "banana", "orange"] ));
Here is a sample: http://jsfiddle.net/rniemeyer/LdeWK/3/
这是一个示例:http: //jsfiddle.net/rniemeyer/LdeWK/3/
The individual fruits do not necessarily need to be observable, unless you need your UI to react to the values changing (your sample does need to react, as you are showing the a read-only list of the fruits).
单个水果不一定需要是可观察的,除非您需要您的 UI 对更改的值做出反应(您的示例确实需要做出反应,因为您正在显示水果的只读列表)。
回答by yoel neuman
here is my hack around:
这是我的黑客:
<!-- ko foreach: list().map(observable => ({ value: observable })) -->
<input type="text" data-bind="value: value">
<!-- /ko -->