Problems with Sort() and knockoutjs

Asked

Viewed 67 times

3

https://jsfiddle.net/n8v3hj5n/1/

I’m having trouble ordering a knockoutjs observableArray, every time I order the list it gives a turn effect().

Who asks to solve this problem?

2 answers

1


Well, the parameter a and b of the Sort is an object, so you must invoke the function as the number is an observable :)

Here’s an example working, I hope you realize what the mistake was !

https://jsfiddle.net/n8v3hj5n/2/

0

Hello, the funcaoDeComparacao(objA, objB) of .sort(funcaoDeComparacao) expects as return an integer to define the array order.

If we compare two objects, the comparison rule returns a small number (relative to the other comparisons), this will be moved to the beginning of the array.

If the return is a larger number (than the other comparisons), it will be moved to the end of the Array.

So to make it easier to compare objects, we usually return -1 when objA should appear before the objB, 0 when objA is equal to objB or 1 when the objA should appear after the objB.

note that the self.numeros is not an array of integers, but an array of objects of the "type" ranum, and this one has a property called numero, it is worth noting that numero also not an integer, but a function that returns a.

Then to perform the ordering in the expected way, do it as follows:

self.organizar = function() {
  self.numeros.sort(function(a, b) {
    var numeroA = a.numero();
    var numeroB = b.numero();
    return numeroA - numeroB;
  });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.