最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Knockout JS - How to correctly bind an observableArray - Stack Overflow

programmeradmin2浏览0评论

Please take a look at this example. /

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

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

Share Improve this question edited Mar 29, 2012 at 21:58 FelipeAls 22.2k9 gold badges56 silver badges74 bronze badges asked Mar 1, 2012 at 4:15 Sam AnthonySam Anthony 1,7493 gold badges24 silver badges39 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

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

here is my hack around:

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

评论列表(0)

  1. 暂无评论