Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a given index element in knockoutjs

Tags:

How do you replace a given index in an observableArray with another element.

I have: ViewModel.Elements()[index]

how can i replace it with another element.

like image 486
user656822 Avatar asked Jun 21 '11 12:06

user656822


People also ask

What is observableArray?

ObservableArray is an array that allows listeners to track changes when they occur. In order to track changes, the internal array is encapsulated and there is no direct access available from the outside. Bulk operations are supported but they always do a copy of the data range.

How do you make an empty array observable?

To clear an observableArray you can set the value equal to an empty array.


2 Answers

observableArrays do have a replace method. This takes in the old item and the new item.

So, you would call it like:

ViewModel.Elements.replace(ViewModel.Elements()[index], yourNewElement); 

Internally, this just sets that index to your new item and calls valueHasMutated() to notify any potential subscribers.

like image 127
RP Niemeyer Avatar answered Oct 04 '22 14:10

RP Niemeyer


It's a little late by now, but I have noticed that this question is still left unanswered (properly).

As the others have stated, the 1st answer does not give the expected behavior, it will replace an item of an observableArray by value and not by index!

The other answers are overly complicated and does not take advantage of Knockout's extended natives.


To truly replace a value in a given index of an observableArray, you should use the splice() method.

var myObservable = ko.observableArray([1, 2, 3, 4]); myObservable.splice(0, 1, 100); // Replace the value at [0] with "100" myObservable.splice(2, 1, 300); // Replace the value at [2] with "300" console.log(myObservable()); // [100, 2, 300, 4] 

And since the splice() method is extended by Knockout, it will automatically notify any dependencies, eliminating the need to call valueHasMutated().

EDIT / February 14th 2016

In case you need to replace multiple values at once, it'll be much quicker to get the underlying array, perform the replacement and then notify changes.

var myObservable = ko.observableArray([1, 2, 3, 4]); var underlyingArray = myObservable();  myObservable.valueWillMutate();  for(...)    underlyingArray[i] = newValue[i];  this.valueHasMutated(); 
like image 45
losnir Avatar answered Oct 04 '22 16:10

losnir