RolandG
RolandG

Reputation: 1329

Using the Knockout mapping plugin on objects with children

Let's say I have this data:

var data = {
    name: 'Graham',
    children: [
        { id : 1, name : 'Lisa' }
   ]
}

Now I map it, add some properties and map it back:

var mappedData = ko.mapping.fromJS(data);
mappedData.age = 44;
mappedData.children[0].age = 12;
var unmappedData = ko.mapping.toJS(mappedData);

In the unmappedData root object, age is not present, but in the child object, it is. This is because the mapping plugin keeps track of the original properties, but only for the root object.

Is there a way, besides using a custom 'create' mapping for every child collection off the root, to turn on this tracking for child collection objects?

Upvotes: 1

Views: 288

Answers (1)

nemesv
nemesv

Reputation: 139758

Probably your only viable option is to use a custom create function for every child collection...

But you don't need to manually create the mapping you can generate the with the using the ko.mapping.visitModel method, something like:

var mapping = {};
ko.mapping.visitModel(data, function(item, parent) {
    if (ko.mapping.getType(item) === "array")
    {
        mapping[parent] = { 
            create: function(op) { return ko.mapping.fromJS(op.data); }
        }
    }
});
var mappedData = ko.mapping.fromJS(data, mapping);

Demo JSFiddle.

Upvotes: 2

Related Questions