为类别和产品创建视图模型。categoryViewModel
应该包含一个添加产品的函数,并且根视图模型应该包含一个添加类别的函数:
根视图模型:
viewModel = function () {
var self = this;
menuItem = menuItem || {
Id: 0,
Name: null,
Categories: []
};
this.Id = ko.observable(menueItem.Id);
this.Name = ko.observable(menueItem.Name);
this.Categories = ko.observableArray();
this.addCategory = function(category) {
self.Categories.push(new categoryViewModel(category));
}
// create category viewmodels and add them to this root viewmodel
for (var i = 0, l = menuItem.Categories.length; i < l; i++) {
self.addCategory(menuItem.Categories[i]);
}
// ...
}
类别视图模型:
categoryViewModel = function(categoryObj) {
var self = this;
categoryObj = categoryObj || {
Id: 0,
Name: null,
Products: [],
};
this.Id = ko.observable(categoryObj.Id);
this.Name = ko.observable(categoryObj.Name);
this.Products = ko.observableArray();
this.addProduct = function(product) {
self.Products.push(new productViewModel(product);
}
// create product viewmodels and add them to this category viewmodel
for (var i = 0, l = categoryObj.Products.length; i < l; i++) {
self.addCategory(categoryObj.Products[i]);
}
}
产品视图模型:
productViewModel = function(productObj) {
var self = this;
productObj = productObj || {
Id: 0,
Name: null,
SomethingElse: null,
};
this.Id = productObj.Id;
this.Name = productObj.Name;
this.SomethingElse = productObj.SomethingElse;
}
你将会拥有:
viewmodel {
Id(),
Name(),
Categories() : [
categoryViewModel = {
Id(),
Name(),
Products(): [
productViewModel = {
Id,
Name,
SomethingElse
}
...
]
},
...
]
}