Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically sort ko.observableArray as bound properties change

Tags:

knockout.js

is there a way to automatically sort an observable array when a bound property is changed? I believe in the following example, my view is updated when i add a new person, but can I get the view to refresh and apply my sorting function if one of the person's age is 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>
like image 390
Anders Nygaard Avatar asked Jun 22 '12 07:06

Anders Nygaard


People also ask

What is observableArray?

An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

How to assign value to Knockout observable?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.


1 Answers

You can subscribe an observable and act whenever that observable changes:

person.age.subscribe(function (newValue) {
    viewModel.someSortFunction();
});
like image 128
Tuan Avatar answered Oct 20 '22 03:10

Tuan