使用Knockout Mapping扩展子对象

时间:2014-02-24 23:22:01

标签: javascript json knockout.js knockout-mapping-plugin

考虑这个JSON对象:

{
    "BusinessModels":[
        { 
            "Id":1,
            "Name":"Business to Business",
            "Businesses":[],
            "ReportTypes":[
                {...},
                {...},
                {
                    "Id":6,
                    "Name":"Risk",
                    "BusinessModelId":1,
                    "Reports":[
                        {
                            "Id": 4,
                            "Name": "Test",
                            "Value": ko.observable() // NEED TO ADD THIS PROPERTY USING MAPPING
                        },
                        {...}
                    ]
                }
            ],
        }
    ]
}

我正在尝试使用以下代码添加该值,但它似乎不起作用。

var mapping = {
    'BusinessModels': {
        create: function(options) {
            return new function() {
                var self = options.data;
                self.SelectedBusiness = ko.observable();
                self.Businesses.unshift({ Id: 0, Name: 'All Clients' });
                ko.mapping.fromJS(self, {}, this);
            };
        }
    },
    'Reports': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.Value = ko.observable();
                ko.mapping.fromJS(options.data, {}, this);
            };
        }
     }
};

var model = ko.mapping.fromJSON(raw, mapping);
ko.applyBindings(model);

我需要给一个子对象“Reports”一个名为ko.observable的{​​{1}}对象。我如何在ko.mapping中执行此操作?

1 个答案:

答案 0 :(得分:0)

嗯,那很快。我想出了答案。

var mapping = {
    'BusinessModels': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.SelectedBusiness = ko.observable();
                self.Businesses.unshift({ Id: 0, Name: 'All Clients' });
                ko.mapping.fromJS(self, mapping, this);
            };
        }
    },
    'Reports': {
        create: function (options) {
            return new function () {
                var self = options.data;
                self.Value = ko.observable();
                ko.mapping.fromJS(self, mapping, this);
            };
        }
    }
};

我使用ko.mapping.fromJS(self, {}, this)而不是ko.mapping.fromJS(self, mapping, this)。原因是Reports是BusinessModels的嵌套对象。