Knockout Repeat plug-in

I had a request to display the newest items added at the top of the table, but in the data storage, the newest items needed to be added at the bottom. The built-in foreach binding in knockout does not have an order option. It always traverses the observable array from 0 to the last item. So, I needed to figure out another option for building the table. One option, using only built-in knockout functionality, was to create a second array and using the reverse function on the array to recreate the second array whenever the first array was updated. I just saw too many possible problems with that and, having 2 copies of data, they were liable to get out of sync.

I searched for options on Stackoverflow and found a Repeat plug-in that had been created by Michael Best. It works similar to foreach, but it does have a reverse option which would do what I need. There are some differences in how they work. The main difference is the context that has scope within the loop. In “foreach”, the context changes to the observable array. So, if I specified “foreach: payments”, within the loop, I would just use “amount”. While using the repeat binding, the context stays with the original parent object. So, if I specified “repeat: {foreach:payments, reverse:true}”, within the loop, I would use “$item().amount” to access properties of the object stored in the observable array.

The differences are very minor, but the functionality provided is quite beneficial. This is a plug-in I highly recommend.

Have a Happy Thanksgiving.

Leave a Reply

Your email address will not be published. Required fields are marked *