Knockout.js mapping options being ignored on neste

2019-07-21 04:00发布

问题:

I am unable to get the knockout.js mapping options to work on nested values. With the following code, the first level "shouldBeCopied" works fine and the nested "shouldBeCopied" value is always an observable.

var data = {
    shouldBeCopied: "copied",
    nested: {
        shouldBeCopied : "copied"
    }
};

var vm = ko.mapping.fromJS(data, {
    'copy': ["shouldBeCopied"],
    "nested": {
        'copy': ["shouldBeCopied"]
    }
});

console.log(vm);

Any ideas?

Here's a fiddle if anyone wants to play around with it.

回答1:

When using the the copy, ignore, observe, etc options you don't need to minic the object structure in your mapping options (like when using create)

What you need to to is to use a property accessor expression ("nested.shouldBeCopied") in your copy array to configure nested properties:

var data = {
    shouldBeCopied: "copied",
    nested: {
        shouldBeCopied : "copied"
    }
};

var vm = ko.mapping.fromJS(data, {
    'copy': ["shouldBeCopied","nested.shouldBeCopied"]
});

Will output:

Demo JSFiddle.