我有一个名为ProductsViewModel
的 View 模型
其中包含 ProductViewModel
ProductViewModel
还包含一个 observableArray - of ProductPriceViewModel
我拥有的一个功能是我可以复制 ProductViewModel
并将其插入到 ProductsViewModel
数组中。
当我克隆时使用:
ko.mapping.fromJS(ko.toJS(itemToCopy));
它似乎没有正确复制 - prices
可观察数组没有填充 ProductPriceViewModel
- 只是对象
这是 View 模型
var ProductsViewModel = function() {
var self = this;
self.products = ko.observableArray([new ProductViewModel()]);
self.addNewProduct = function() {
self.products.push(new ProductViewModel());
};
self.duplicateProduct = function() {
var itemToCopy = ko.utils.arrayFirst(self.products(), function(item) {
return item.visible();
});
//if i look at itemToCopy.prices() it is an array of ProductViewModel
var newItem = ko.mapping.fromJS(ko.toJS(itemToCopy));
//if i look at newItem.prices() it is an array of Object
self.products.push(newItem);
};
};
var ProductViewModel = function() {
var self = this;
self.name = ko.observable();
self.visible = ko.observable(true);
self.prices = ko.observableArray([new ProductPriceViewModel()]);
self.addPrice = function() {
self.prices.push(new ProductPriceViewModel());
};
};
var ProductPriceViewModel = function() {
var self = this;
self.name = ko.observable();
self.price = ko.observable();
};
最佳答案
我通过传递这样的映射配置解决了这个问题:
var mapping = {
'prices': {
create: function (options) {
return new ServicePriceViewModel(options.data);
}
}
};
开
var newItem = ko.mapping.fromJS(ko.toJS(productToCopy), mapping);
并更改我的 ProductPriceViewModel
以接受数据作为参数:
var ProductPriceViewModel = function (data) {
var self = this;
self.name = ko.observable();
self.description = ko.observable();
self.price = ko.observable();
self.priceIsFrom = ko.observable();
if (data)
ko.mapping.fromJS(data, {}, this);
};
关于javascript - 使用 Knockout 克隆具有可观察数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21525950/