Knockout.js mapping options being ignored on neste

2019-07-21 03:59发布

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条回答
聊天终结者
2楼-- · 2019-07-21 04:17

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:

enter image description here

Demo JSFiddle.

查看更多
登录 后发表回答