Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top