简体   繁体   English

复杂对象传递到ko.mapping.fromJS

[英]Complex Object passed into ko.mapping.fromJS

I have a complex object I want to pass into ko.mapping.fromJS and my problem is that I only want one field to be observable, but the other properties come across as either null or non-existent based on the methods I have tried. 我有一个复杂的对象,我想传递给ko.mapping.fromJS ,我的问题是我只想要一个字段是可观察的,但其他属性根据我尝试过的方法得到null或不存在。

I have created a jsFiddle here to illustrate my problem. 我在这里创建了一个jsFiddle来说明我的问题。 I wish for the inner object to simply be copied as I have no need for it to be observable; 我希望简单地复制内部对象,因为我不需要它是可观察的; I don't want the extra overhead considering the number of these I will have. 考虑到我将拥有的这些数量,我不想要额外的开销。

The goal of this would be to make the qty editable, but the inner.name remain the same in the text box. 这样做的目的是使qty可编辑,但inner.name在文本框中保持不变。 This would mean that one is an observable while the other is not. 这意味着一个是可观察的,而另一个则不是。

If any one has another way of doing it that does not involve the mapping I would love to hear it. 如果任何一个人有另一种方式,这不涉及映射,我很乐意听到它。 My view model has quite a few functions and such, and the data is coming in from an AJAX call. 我的视图模型有很多功能等,数据来自AJAX调用。

function viewModel() {
    var self = this;
    self.slots = ko.observableArray([]);

    self.load = function() {
        ko.mapping.fromJS(
            [
                { 'qty': 1, 'inner': { 'name': 'thing'} },
                { 'qty': 2, 'inner': { 'name': 'stuff'} }
            ],
            { 'include': ['qty'], 'ignore': ['inner.name'] },
            self.slots);
    }
};

ko.applyBindings(new viewModel());

<button data-bind="click: load">Go</button>
<ul data-bind="foreach: slots">
    <li>
        <span data-bind="text: qty"></span>&nbsp;<span data-bind="text: inner.name"></span><input data-bind="value: qty" /><input data-bind="value: inner.name" />
    </li>
</ul>

You need to use copy instead of ignore because you want to have properties there just not be observable. 你需要使用copy而不是ignore因为你想拥有那些不可观察的属性。

And because you are mapping directly an array the mapping configuration becomes a little bit complicated. 而且因为您直接映射数组,映射配置变得有点复杂。

You cannot define copy on the "root" level because you have the array at the root. 您无法在“根”级别定义copy ,因为您在根目录中拥有该阵列。 So you have to supply a create function for the items and in the create function you can now specify the copy options for the properties of the item: 因此,您必须为项目提供create功能,现在您可以在创建功能中指定项目属性的copy选项:

   ko.mapping.fromJS(
        [
            { 'qty': 1, 'inner': { 'name': 'thing'} },
            { 'qty': 2, 'inner': { 'name': 'stuff'} }
        ],
        {
            create: function (options) {
                return ko.mapping.fromJS(options.data, {
                    copy: ['inner.name']
                })
            }
        },
        self.slots);

Demo JSFiddle. 演示JSFiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM