-1

I'm trying to reset a knockout observable array in my view model to contain nothing, yet I'm being stonewalled at every turn. When it is defined, I set it empty:

self.currentPeople = ko.observableArray([]);

Yet if I try to alter it down the page:

self.currentPeople.removeAll();

I get the exception:

Uncaught TypeError: undefined is not a function

Even if I do a safe check to see if it exists and then set it:

 if (self.currentPeople ) {
       self.currentPeople.removeAll();
 } else {
       self.currentPeople = ko.observableArray([]);
 }  

I still receive the same error. What am I doing wrong?

marked-down
  • 9,958
  • 22
  • 87
  • 150

2 Answers2

1

If by contain nothing and clear array you mean contain an empty array you simply do:

self.currentPeople([]);

On a side note, testing with

if(someObservable)

Will always return true, to test if it contains anything use "someObservable()". That will get the observables value instead of the wrapper. I am confused though by how self.currentPeople.removeAll() throws an error, could you post more of your code if the above solution does not work out for you, and clarify what you need?

I am aware half of this answer should be a comment but I do not have the rep to do so yet.

HotTowelie
  • 123
  • 8
-1

You need to 'de-reference' your observable array by saying self.currentPeople().removeAll()

Daryl
  • 610
  • 1
  • 7
  • 17
  • 2
    [No you don't](http://knockoutjs.com/documentation/observableArrays.html#remove-and-removeall), and in fact if you work on the underlying array in this way, knockout won't see the change you make either. – James Thorpe Jan 21 '15 at 20:44