1

How do I get a copy of items in knockout observable array. Changing the copied items should not affect the original item.

What I want to do is before opening a popup, create a copy of item when the user clicks cancel button reload the original values

ColinE
  • 68,894
  • 15
  • 164
  • 232
Techonthenet
  • 157
  • 4
  • 12

2 Answers2

1

You can just use standard JavaScript techniques to clone your array. See the following:

Copying array by value in JavaScript

So, you can copy as follows:

var newArray = viewModel.observableArray().slice(0);
Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232
  • Yes. This worked. But when make changes to original array the destination array also changed. Any way to avoid this? – Techonthenet Apr 24 '13 at 09:42
  • Can you please explain this one? Share.Product = new SharedModel(data) { var this=data; self.myid=ko.observable(data.id); // an so on.. }("Mentor.Shared.Product", jquery) Share.ViewModel= new functionalmodel(data) { var this=data; self.name=ko.observable(data.name); }("Mentor.Shared.Product", jquery) How this binding is applied in knockout. Can some please explain. I see lot of this types code in the project and I am unfamiliar with the code. I am trying to under stand it hardly. – Techonthenet Apr 27 '13 at 09:09
0

The following is used to create a copy of the JS array.

var newArray = viewModel.observableArray().slice(0); ?/copies the internal array
viewModel.copyobservableArray(newArray); // set in new observable

For ko observableArray we need to do the following to make it new copy

If the internals of the array are also objects then you should probably clone those too to avoid the pass by reference.

Jerin Joseph
  • 759
  • 1
  • 7
  • 22