Knockout JS - 如何正确绑定observableArray [英] Knockout JS - How to correctly bind an observableArray

查看:102
本文介绍了Knockout JS - 如何正确绑定observableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看一下这个例子。
http://jsfiddle.net/LdeWK/2/

Please take a look at this example. 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是实际值,而不是通常绑定的可观察函数。
这看起来应该是一个非常直接的过程,但我无法弄清楚。

$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.

在其他情况下,我使用了可观察数组并且有一个可观察的数据object作为可观察数组的每个元素。我想知道如何使用可观察数组来实现这一点。

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.

谢谢

推荐答案

如果您对数组或observableArray中的项进行读/写绑定,则它们将需要是对象的属性。否则, $ data 将是未包装的observable,并且KO无法写入实际的observable。

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.

您必须执行以下操作:

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"] )); 

以下是一个示例:http://jsfiddle.net/rniemeyer/LdeWK/3/

个别水果不一定需要观察,除非你需要你的UI来对变化的值做出反应(你的样本确实需要做出反应,因为你显示的是水果的只读列表)。

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).

这篇关于Knockout JS - 如何正确绑定observableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆