0

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());
skmasq
  • 4,470
  • 6
  • 42
  • 77
  • 2
    You created a _shallow_ clone of an array. So each array contains the same references to the objects the original array was referring to. I suppose you wanted to make a deep clone... – Jeff Mercado Apr 24 '14 at 04:17
  • @JeffMercado Yes you're correct. I updated my question to include answer. – skmasq Apr 24 '14 at 04:18
  • No don't do that, if you have an answer to your question, post it as an answer. – Jeff Mercado Apr 24 '14 at 04:19

1 Answers1

1

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));
}
Community
  • 1
  • 1
skmasq
  • 4,470
  • 6
  • 42
  • 77