Reverse Array in Knockout.js

I am learning how to use Knockout.js. I want to show the reversible value of the observable array, so I use the Knockout inverse function as follows:

<ul data-bind="foreach: anObservableArray.reverse()" >...</ul> 

But this does not work and no errors occur. When I try this:

 <ul data-bind="foreach: anObservableArray.slice(0).reverse()" >...</ul> 

It works as expected. My question is why do I need to copy the entire array when the inverse function already returns the reversible array?

+6
source share
3 answers

A reverse call will actually change the array in place (and return it), so you may run into a problem when it accesses several times.

For example, if you have two blocks, for example:

 <ul data-bind="foreach: anObservableArray.reverse()" >...</ul> <ul data-bind="foreach: anObservableArray.reverse()" >...</ul> 

The first will be canceled, and the second will return to the original order.

It is better to cancel the copy, especially if you will add and remove elements from the array.

+6
source

I got this from my search on this subject, the reason why you now need to copy the array,

"A change was made to knockout.js 2.2 to force the mutation functions of the array not to depend on the observed array. Usually, if you want the computed reverse version of the array to have a reverse version, you will not use reverse in the original array but on the copy. self.anObservableArray.reverse() do self.anObservableArray.slice(0).reverse() Example: http://jsfiddle.net/mbest/3QHM7/1/

Thus, basically, you need to avoid creating a dependency on the observed array.

+3
source

Since reverse () takes effects on the original array instead of returning, the array of copies and the knockout call it two times with the "foreach" binding, so you get the same array in the end result.

You can check this code:

 <ul data-bind="foreach: alert(anObservableArray.reverse())" >...</ul> 
+1
source

All Articles