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>
An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.
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.
You can subscribe an observable and act whenever that observable changes:
person.age.subscribe(function (newValue) {
viewModel.someSortFunction();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With