Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

javascript - Knockout JS - How to correctly bind an observableArray

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...