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

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

问题描述

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

我想知道如何绑定可观察数组的值.我知道上面例子中的问题,就是这一行

<p>编辑水果:<input data-bind="value: $data"/></p>

$data 是实际值,而不是您通常会绑定的可观察函数.这看起来应该是一个非常直接的过程,但我无法弄清楚.

在其他情况下,我使用了 observable 数组,并且有一个 observable 对象作为 observable 数组的每个元素.我想知道如何让它仅与可观察数组一起工作.

谢谢

解决方案

如果您将读/写绑定到数组或 observableArray 中的项目,那么它们将需要是对象的属性.否则,$data 将是解包的 observable,KO 无法写入实际的 observable.

您必须执行以下操作:

var ViewModel = function(myFruit) {var observableFruit = ko.utils.arrayMap(myFruit, function(fruit) {返回{名称:ko.observable(水果)};});this.fruit = ko.observableArray(observableFruit);};ko.applyBindings(new ViewModel(["Apple", "banana", "orange"]));

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

单个水果不一定需要可观察,除非您需要您的 UI 对更改的值做出反应(您的示例确实需要做出反应,因为您显示的是水果的只读列表).

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

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. Otherwise, $data will be the unwrapped observable and there is no way for KO to write to the actual 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/

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天全站免登陆