Pregunta

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());
¿Fue útil?

Solución

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));
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top