Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  191] [ 5]  / answers: 1 / hits: 17355  / 13 Years ago, thu, march 1, 2012, 12:00:00

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


More From » knockout.js

 Answers
22

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


[#87125] Wednesday, February 29, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karolinab

Total Points: 644
Total Questions: 98
Total Answers: 117

Location: Vanuatu
Member since Mon, Dec 7, 2020
4 Years ago
;