Consider this JSON object:
{
"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
},
{...}
]
}
],
}
]
}
I'm trying to add the value using the following code, but it doesn't seem to work.
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);
I need to give a child object "Reports" a ko.observable
object named Value
. How do I go about doing this in ko.mapping?
Well, that was quick. I figured out the answer.
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);
};
}
}
};
Rather than using ko.mapping.fromJS(self, {}, this)
I used ko.mapping.fromJS(self, mapping, this)
. The reason is because Reports is a nested object of BusinessModels.