我有一个名为ProductsViewModel的视图模型
它包含一个ProductViewModel的observableArray

ProductViewModel还包含一个ProductPriceViewModel的observableArray-

我的一个功能是可以复制ProductViewModel并将其插入ProductsViewModel数组。

当我使用克隆时:

ko.mapping.fromJS(ko.toJS(itemToCopy));


它似乎不能正确复制-prices可观察的数组,没有填充ProductPriceViewModel-只是对象

这是视图模型

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

09-18 03:35