Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy items from observablearray to another observablearray

Tags:

knockout.js

I have 2 observablearray. When I copy items from observablearray1 to observablearray2, and change value in observablearray2, in changes in observablearray1 too.

var viewModel = (function() {
    var
        array1 = ko.observableArray(['John', 'Joe', 'Jim']),
        array2 = ko.observableArray();

    // copy
    array2(array1());
    array2()[2] = 'Mary';
    return {
        array1: array1,
        array2: array2
    }

})();

ko.applyBindings(viewModel);

console.log(viewModel.array1());
console.log(viewModel.array2());

http://jsfiddle.net/xveEP/69/

Results:
array 1
John
Joe
Mary
array 2
John
Joe
Mary

How to fix it? Thanks

like image 260
Alex Zahorodniy Avatar asked Oct 12 '13 21:10

Alex Zahorodniy


1 Answers

Copy the elements of the array instead of the array itself:

// copy
for (var i = 0; i < array1().length; i++) {
    array2().push(array1()[i]);
}
like image 115
Matthias Avatar answered Sep 23 '22 01:09

Matthias