我希望能够将传入的数据向下映射到子对象及其可观察数组,并访问子对象中的可观察对象(在此示例中:Main-> BikeShop()。BikeShopExtra())。
看来我可以有一个,但不能两个都有。在下面的示例中,它在Main对象的这一行上失败。
self.MainTest = ko.observable(self.BikeShop().BikeShopExtra());
我要的结构是这样的: 应用-初始化主 Main-包含所有业务逻辑,类似于MVC模式中的控制器 BikeShop和客户-DTO,类似于MVC模式中的视图模型
我遇到的问题有一个残缺的骨架示例: 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);