How do I make a deep copy of a knockout object that was created by the mapping plugin

烂漫一生 提交于 2019-12-02 20:28:49

There might be a way to set this up in the mapping settings but I can't quite figure that out just yet.

In the mean time, you could just unmap the object and map it back so you are essentially making a copy.

var newJob = ko.mapping.fromJS(ko.mapping.toJS(job));

This will be the easiest way to do it just like any other library, "deserialize" and "serialize" back again.


I was looking hard for a nice way to do this using the mapping options and found a way.

By default, the mapping plugin will take the observable instances from the source object and use the same instance in the target object. So in effect, both instances will share the same observables (bug?). What we needed to do was create a new observable for each property and copy the values over.

Fortunately, there is a handy utility function to map out each of the properties of an object. We can then create our new observable instances initialized with copies of the values.

// Deep copy
var options = {
    create: function (options) {
        // map each of the properties
        return ko.mapping.visitModel(options.data, function (value) {
            // create new instances of observables initialized to the same value
            if (ko.isObservable(value)) { // may want to handle more cases
                return ko.observable(value);
            }
            return value;
        });
    }
};
var newJob = ko.mapping.fromJS(job, options);

Note that this will be a shallow copy, you'll probably have to recursively map the objects if you want a deep copy. This will fix the problem in your example however.

Teddy
ko.utils.clone = function (obj) {
    var target = new obj.constructor();
    for (var prop in obj) {
        var propVal = obj[prop];
        if (ko.isObservable(propVal)) {
            var val = propVal();
            if ($.type(val) == 'object') {
                target[prop] = ko.utils.clone(val);
                continue;
            }
            target[prop](val);
        }
    }
    return target;
};

Here is my solution, hope it helps. In this code, obj would be your viewModel object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!