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.
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.
To clear an observableArray you can set the value equal to an empty array.
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.
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()
.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With