简体   繁体   English

Knockout JS - 如何正确绑定observableArray

[英]Knockout JS - How to correctly bind an observableArray

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. $ data是实际值,而不是您通常绑定的可观察函数。 This seems like it should be a pretty straight forward process, however I cant figure it out. 这似乎应该是一个非常直接的过程,但我无法弄明白。

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. 我想知道如何使用可观察的数组来实现它。

Thanks 谢谢

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. 如果绑定读/写数组中的项或observableArray,则它们将需要是对象的属性。 Otherwise, $data will be the unwrapped observable and there is no way for KO to write to the actual observable. 否则, $data将是unwrapped 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对变化的值作出反应(你的样本确实需要做出反应,因为你显示的是水果的只读列表)。

here is my hack around: 这是我的黑客:

<!-- ko foreach: list().map(observable => ({ value: observable })) -->
    <input type="text" data-bind="value: value">
<!-- /ko -->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM