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.
You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).
To trigger an element deletion, simply send an event on the subject: this. deleteSubject. next({op:'delete', id: '1'});
Description. The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.
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
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