Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 862
Sam Anthony Avatar asked Mar 01 '12 04:03

Sam Anthony


1 Answers

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

like image 148
RP Niemeyer Avatar answered Oct 09 '22 22:10

RP Niemeyer