I would like to be able to map the incoming data down to the child objects and their observable arrays and access observables in child objects (in this example: Main -> BikeShop().BikeShopExtra()).
It seems I can have one or the other, but not both. In the example below, it fails on this line of the Main object.
self.MainTest = ko.observable(self.BikeShop().BikeShopExtra());
The structure I am going for is this: App - Initializes Main Main - Contains all of the business logic, similar to a controller in MVC pattern BikeShop and Customer - DTOs, similar to a view model in MVC pattern
I have a broken skeleton example of the issue I am having: https://jsfiddle.net/Mason240/36gh20p8/52/
window.Application = window.Application || { Config: {}, Models: { }, Mappings: { } };
window.Application.App = (function ($, ko) {
var init = function (opts) {
var vm = new Application.Models.Main();
ko.mapping.fromJS(opts.model, Application.Mappings.Main, vm);
ko.applyBindings(vm);
};
return {
Init: init
};
}(jQuery, ko));
window.Application.Models.Main = function () {
var self = this;
self.BikeShop = ko.observable();
self.MainTest = ko.observable(self.BikeShop().BikeShopExtra());
};
window.Application.Models.BikeShop = function () {
var self = this;
self.Id = ko.observable();
self.StoreName = ko.observable();
self.Customers = ko.observableArray([]);
self.CompoundId = ko.computed({
read: function () {
return self.Id() + "-" + self.StoreName();
}
});
self.BikeShopExtra = ko.observable("Bike Shop Extra");
};
window.Application.Models.Customer = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.CompoundId = ko.computed({
read: function () {
return self.Id() + "-" + self.Name();
}
});
self.CustomerExtra = ko.observable("Customer Extra");
};
window.Application.Mappings.Main = {
'BikeShop': {
create: function (obj) {
var model = new Application.Models.BikeShop();
ko.mapping.fromJS(obj.data, Application.Mappings.BikeShop, model);
return model;
}
}
};
window.Application.Mappings.BikeShop = {
'Customers': {
key: function (data) {
return ko.utils.unwrapObservable(data.Id);
},
create: function (obj) {
var model = new Application.Models.Customer();
if (obj.data) {
ko.mapping.fromJS(obj.data, {}, model);
}
return model;
}
}
};
(function ($) {
Application.App.Init({
"model" : {
"BikeShop": {
"Id": 79605,
"StoreName": "Valley Bike",
"Customers": [
{
"Id": 54132123,
"Name": "Greg"
},
{
"Id": 78906344,
"Name": "Mason"
}]
}
}
});
})(jQuery);