gpt4 book ai didi

javascript - Knockoutjs 嵌套的 observableArrays

转载 作者:行者123 更新时间:2023-11-29 19:34:32 27 4
gpt4 key购买 nike

我在删除嵌套的 observableArrays 时遇到了一些麻烦。

我的数据是这样的:

var myData = {
Id: 123,
Name: "string here",
Categories: [
{
Id: 12,
Name: "Category Name",
Products: [
{
Id: 1,
Name: 'Product1 name',
SomethingElse: '...'
},
{
Id: 2,
Name: 'Product2 name',
SomethingElse: '...'
}
]
},{
// another category ...
}
]
}

我的 ViewModel 看起来像这样:

 viewModel = function () {
var self = this;
this.Id = menueItem ? ko.observable(menueItem.Id) : ko.observable(0);
this.Name = menueItem ? ko.observable(menueItem.Name) : ko.observable();
this.Categories = menueItem ? ko.observableArray(menueItem.Categories) : ko.observableArray([]);
// ...
}

所以我的问题是,如何将每个 CategoryProducts 也获取到 observableArray。Products 中的属性不必是可观察的。在我的应用程序中,我必须添加和删除类别和产品。

最佳答案

为类别和产品创建 View 模型。 categoryViewModel 应该包含一个添加产品的函数, Root View 模型应该包含一个添加类别的函数:

Root View 模型:

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]);
}
// ...
}

类别 View 模型:

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]);
}
}

产品 View 模型:

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
}
...
]
},
...
]
}

关于javascript - Knockoutjs 嵌套的 observableArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25784715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com