knockout.mapping
knockout.mapping copied to clipboard
Create observable from the array elements
Imaging I have the following data:
{
items: [1, 2, 3]
}
Then I init my view model:
var vm = ko.mapping.fromJS(data);
ko.applyBindings(vm);
I need to be able to make 2-way binding to individual array elements, e.g. data-bind="value: items[0]"
This only works one-way: when I change the value of the input, it is not reflected in the view model - see the demo http://jsfiddle.net/MDbR4/1/
Is there a way to make the elements of the 'items' array observable?
I'm with the same doubt. I've an array of strings. I can bind and add items, but when I change the item, value is not updated on the arrey
To make the items in the array observable you may use mapping options:
vm = ko.mapping.fromJS(data, {
items: {
create: function(options) {
return ko.observable(options.data);
}
}
});
Updated example: http://jsfiddle.net/4afjxh8y/