I'm trying to replace all of the contents of an item in an observableArray
with new content.
var oldLocation = ko.utils.arrayFirst(self.locations(), function (item) {
return item.id == value.id;
});
self.locations.replace(self.locations.indexOf(oldLocation), new location(value));
self.locations.valueHasMutated();
I've also tried
self.locations[self.locations.indexOf(location)] = new fizi.ko.models.location(value);
But nothing is working. The index is being properly retrieved but the update of the item isn't happening.
I simply want to mention an alternative way to do it:
Knockout includes
splice
in its documentation, but doesn't includereplace
: Knockout Obervable Arrays Docs. However, if you look at the source code you'll see that both functions are implemented (at least in KO 3.0, I don't know ifreplace
was missing in previous versions).I'm not aware of a replace method in JavaScript for arrays, or in Knockout. Am I missing something?
If you want to use your second method, then you need to access locations as an observable:
though you don't when using indexOf, as there is a Knockout version of that for observable arrays.
The replace function accepts two parameters, the item you want to replace and the new item you want to replace it with. You are passing in the index in place of the item to replace so it doesn't work.
The replace call should be:
On a side note, you shouldn't need the
valueHasMutated()
call there, it will get invoked by thereplace()
call.