Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout observable array remove after index

I'm looking for a way in knockout to remove all the elements in an observable array which come after a given index.

A for-loop to do that is inefficient since removing one element at a time triggers change notifications with every removal. Is there anything out of the box ?

like image 292
Diana Ionita Avatar asked Mar 06 '26 06:03

Diana Ionita


1 Answers

Try this (note that HowMany is optional and if you don't specify it, all the items after StartIndex will be removed):

myObservableArray.splice(StartIndex, HowMany)

If you need to remove items that have certain properties, you can pass a function returning a boolean value to knockout's remove function, for example:

myObservableArray.remove(function(item) { return item.property > YourValue })

+ Quote from knockout docs: LINK

Normally, an observableArray notifies its subscribers immediately, as soon as it’s 
changed. But if an observableArray is changed repeatedly or triggers expensive updates,
you may get better performance by limiting or delaying change notifications. This is
accomplished using the rateLimit extender like this:

// Ensure it notifies about changes no more than once per 50-millisecond period
myViewModel.myObservableArray.extend({ rateLimit: 50 });
like image 102
szpic Avatar answered Mar 08 '26 20:03

szpic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!