Automatically sort ko.observableArray with change related properties

Is there a way to automatically sort the observed array when the binding property changes? I believe in the following example, my view is updated when I add a new person, but can I get a view to update and apply my sort function if one of the person's ages has changed?

person = { age: ko.observable(); } viewModel = { people: ko.observableArray([]), someSortFunction: function() { this.people.sort(function(person1, person2) { return person2.age() - person1.age(); }); } } <div data-bind="foreach: people"> <span data-bind="text: age"/> </div> 
+6
source share
1 answer

You can subscribe to observables and act whenever observable changes:

 person.age.subscribe(function (newValue) { viewModel.someSortFunction(); }); 
+4
source

Source: https://habr.com/ru/post/918730/


All Articles