knockout.mapping icon indicating copy to clipboard operation
knockout.mapping copied to clipboard

Create observable from the array elements

Open amakhrov opened this issue 12 years ago • 2 comments

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?

amakhrov avatar Aug 05 '13 14:08 amakhrov

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

rsantosdev avatar Sep 03 '13 12:09 rsantosdev

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/

crissdev avatar Feb 23 '15 16:02 crissdev