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 badges2 Answers
Reset to default 18If 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 -->