Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeAll vs empty an array with [] in knockoutjs

Tags:

knockout.js

I want to throw away the data in my observablearray everytime I get data from my server.

What is the difference in functionality between

self.myArray([]); 

vs

self.myArray.removeAll(); 
like image 932
msfanboy Avatar asked Jul 09 '13 10:07

msfanboy


People also ask

How do you clear an array in knockout JS?

The KnockoutJS Observable removeAll() method removes all items and returns them as an array.

How do you clear an observable array?

To clear an observableArray you can set the value equal to an empty array.

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

From the end result point of view there is no difference between the two call, so you will end up with myArray containing no elements.

However there is one small difference (if you don't care about the different return values):

self.myArray([]); 

will replace the underlying array instance with a newly created empty array.

While the

self.myArray.removeAll(); 

will remove all the items from the underlying array but it will keep the array instance.

So if you have multiple ko.observableArray using the same underlaying array you can see the difference between the two calls:

Demo JSFiddle.

like image 108
nemesv Avatar answered Nov 05 '22 05:11

nemesv