Knockoutjs ObservableArrays and Sort Function: UI Not Updated

In my view model, I have an ObserableArray knockout. As soon as I initialized the ViewModel, it successfully binds the data. Then I need to sort the collection.

$.each(vm.searchResults(), function (i, property) { console.log(property.Name()); }); vm.searchResults().sort(function (a, b) { return a.Name().toLowerCase() > b.Name().toLowerCase() ? 1 : -1; }); $.each(vm.searchResults(), function (i, property) { console.log(property.Name()); }); 

As you can see, I output the element name to the console to see the order before and after sorting. Sorting works fine. The problem is updating the user interface. One way or another, the user interface is not updated.

Then try deleting the entry from the array with the following code to see if the user will respond to this or not:

 vm.searchResults().shift(); 

The user interface remains the same and has not been updated again. What is the problem?

Edit:

Here is an example: http://jsfiddle.net/tugberk/KLpwP/

Same problem here.

Edit:

I solved the problem as shown in this example: http://jsfiddle.net/tugberk/KLpwP/16/ But I still don't know why this worked when I tried at the beginning.

+6
javascript ko.observablearray
May 7 '12 at 10:01
source share
1 answer

You expand the observed array when you are going to sort it. This causes problems because KO was not able to track the array. ko.observableArray() has a sort function with the same signature and notifies observable subscribers that it has been changed. The solution is very simple: remove the brackets vm.searchResults().sort => vm.searchResults.sort . Checkout in my example: http://jsfiddle.net/RbX86/

Another way to tell KO that the array has changes is to call the valueHasMutated method after manipulating the array. Check out this example: http://jsfiddle.net/RbX86/1/ This approach is very good when you need to make many changes to your array and you want to update the interface only once.

+18
May 7 '12 at 10:28
source share



All Articles