Computed knockout array not updating

I ran into a problem that the computed observable array is not updated when a new element is added.

self.FilteredCityList = ko.computed(function() { var filteredCollection = ko.utils.arrayFilter(self.CityListCollection(), function(r) { var matchingItem = ko.utils.arrayFilter(self.LocationCollection(), function(r1) { return r1.LocationCode() == r.LocationCode(); }); if (matchingItem.length > 0) { return false; } return true; }); return filteredCollection; }, this); 

When I add an element to self.LocationCollection() , the computed array is not updated.

+4
source share
1 answer

You mentioned in your comment that you used the following code to add elements to your LocationCollection , which caused your problem:

 self.LocationCollection().push(item); 

Where

 self.LocationCollection = ko.observableArray(); 

To enable tracking of knockout changes, you need to directly call push on an observableArray (for example, without a parenthesis () ) as described in the documentation :

 self.LocationCollection.push(item); 

But what is the difference?

Calling ko.observableArray() returns a function. To get the base array, you need to call this function (for example, self.LocationCollection() ), which returns the stored array.

At this point, when you call LocationCollection().push(item) , you call push in the base array so that the knockout does not know about it and it does not start your computed observable.

That's why they knocked out their own push method on the observableArray itself, which you need to call using the syntax LocationCollection.push(item) , but because it will knock out the method, it will track changes correctly.

Sample script.

+9
source

All Articles