Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an array in Knockout.js

Tags:

knockout.js

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?.

like image 302
Leboart Ramgara Avatar asked Jan 18 '13 03:01

Leboart Ramgara


3 Answers

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.

like image 188
RP Niemeyer Avatar answered Nov 14 '22 04:11

RP Niemeyer


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.

like image 20
user3286962 Avatar answered Nov 14 '22 02:11

user3286962


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>
like image 30
Nguyen Manh Dzung Avatar answered Nov 14 '22 02:11

Nguyen Manh Dzung