문제

Basically what I read and what I used thus far for cloning an array without any references in between is something like this:

var clonedArray = ko.observableArray(originalArray().slice(0));

But in this following example it does not seem to work:

var field = function(settings){
  var _self = this;
    _self.Id = settings.Id;
    _self.Flag = ko.observable(settings.Flag);
    return _self;
};

var viewModel = function(){
 var _vm = this;

    _vm.fields = ko.observableArray([
        new field({Id: 1, Flag: true}),
        new field({Id: 2, Flag: false})
    ]);

    _vm.fieldsCloned = ko.observableArray(_vm.fields().slice(0));

    return _vm;
};

ko.applyBindings(new viewModel());
도움이 되었습니까?

해결책

Answer

Reference to this answer

I was faced with the same task; to clone an observable array. The only why I could figure out how to do it, is to convert the observable to an JS object, then convert that object to an observable object. The following function requires KnockoutJS mapping plugin: http://knockoutjs.com/documentation/plugins-mapping.html

function cloneObservable(observableObject) {
    return ko.mapping.fromJS(ko.toJS(observableObject));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top