使用具有可观察数组的Knockout克隆对象

时间:2014-02-03 11:17:59

标签: javascript knockout.js

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

的observableArray

ProductViewModel还包含一个observableArray - ProductPriceViewModel

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

当我使用:

克隆时
ko.mapping.fromJS(ko.toJS(itemToCopy));

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

这是视图模型

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

1 个答案:

答案 0 :(得分:1)

我通过传递这样的映射配置解决了这个问题:

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