Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing item in observableArray

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.

like image 938
bflemi3 Avatar asked Mar 15 '13 19:03

bflemi3


People also ask

How do you update items in observableArray knockout?

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 :).

How do you remove an element from an observable array?

To trigger an element deletion, simply send an event on the subject: this. deleteSubject. next({op:'delete', id: '1'});

How do I sort knockout observable array?

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.


1 Answers

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

like image 173
Jeff Mercado Avatar answered Oct 06 '22 14:10

Jeff Mercado