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

前端 未结 2 1021
不思量自难忘°
不思量自难忘° 2021-02-02 11:26

Here\'s my scenario. I\'m using the knockout mapping plugin to create an observable viewmodel hierarchy for me. My hierarchy has nested elements in it. At a particular point

2条回答
  •  囚心锁ツ
    2021-02-02 11:54

    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.

提交回复
热议问题