Knockout JS – How to correctly bind an observableArray

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

Leave a Comment