I'm learning how to use Knockout.js. I want to show the observableArray content reversed, so I use the Knockout reverse function this way:
<ul data-bind="foreach: anObservableArray.reverse()" >...</ul>
But, it doesn't work and no errors occurs. When I try this:
<ul data-bind="foreach: anObservableArray.slice(0).reverse()" >...</ul>
It works as expected. My question is why should I have to copy the entire array when the reverse function already returns an reversed array?.
Calling reverse
will actually reverse the array in-place (and return it), so you could be running into an issue where it is getting reversed multiple times.
For example, if you had two blocks like:
<ul data-bind="foreach: anObservableArray.reverse()" >...</ul>
<ul data-bind="foreach: anObservableArray.reverse()" >...</ul>
The first would be reversed and the second would be back to the original order.
Better to reverse the copy, especially if you will be adding and removing items from the array.
I got this from my search on this question;reason why it is now necessary to copy the array,
"There was a change in knockout.js 2.2 to make array mutation functions not create a dependency on the observable array. Generally if you want a computed to return a reversed version of the array you will not use reverse on the original array but on a copy. Instead of
self.anObservableArray.reverse()
,
do
self.anObservableArray.slice(0).reverse()
Example: http://jsfiddle.net/mbest/3QHM7/1/
So basically, it is to avoid creating dependency on the observable array.
Because reverse() take effects on the source array instead of return a copy array and knockout call it two times with 'foreach' binding so you will get the same array at the final result.
You can test with this code:
<ul data-bind="foreach: alert(anObservableArray.reverse())" >...</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With