Replacing item in observableArray

26,195

Solution 1

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:

self.locations.replace(oldLocation, new location(value));

On a side note, you shouldn't need the valueHasMutated() call there, it will get invoked by the replace() call.


Side note, many of the native Array functions are available for observable arrays. They are forwarded to the underlying array value triggering notifications of mutations as needed. These include:

pop, push, reverse, shift, sort, splice, unshift, slice (readonly).

Knockout provides these additional methods which should be documented here (currently v3.5.1):

remove, removeAll, destroy, destroyAll, indexOf, replace, sorted, reversed

Solution 2

I simply want to mention an alternative way to do it:

self.locations.splice(
  self.locations.indexOf(location),   // Index of the 1st element to remove
  1,                                  // Number of elements to remote at this index
  new fizi.ko.models.location(value)  // A param for each element to add at the index
);

Knockout includes splice in its documentation, but doesn't include replace: 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 if replace was missing in previous versions).

Solution 3

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:

self.locations()[self.locations.indexOf(location)] = new fizi.ko.models.location(value);
self.locations.valueHasMutated();

though you don't when using indexOf, as there is a Knockout version of that for observable arrays.

Share:
26,195
bflemi3
Author by

bflemi3

Updated on November 14, 2020

Comments

  • bflemi3
    bflemi3 over 3 years

    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.