I have the following view model:
function instance(id, FirstName){
$.extend(this, {
id: ko.observable(id || ''),
FirstName: ko.observable(FirstName || '')
});
}
I have some instances in an observableArray:
ko.observableArray([new instance(...), new instance(...), ...]
With the following template:
<ul data-bind='template: {name: "instanceTemplate", foreach: instances}'></ul>
And another template:
<ul data-bind='template: {name: "anotherInsTmpl", foreach: instances}'></ul>
In first ul
I need to render templates without sorting, in the second one render sorted by FirstName.
Can anyone explain how to do it?
One option would be to add a dependentObservable that represents the sorted array. It would look something like:
viewModel.sortFunction = function(a, b) {
return a.FirstName().toLowerCase() > b.FirstName().toLowerCase() ? 1 : -1;
};
viewModel.sortedInstances = ko.dependentObservable(function() {
return this.instances.slice().sort(this.sortFunction);
}, viewModel);
So, do a case insensitive comparison of the value of the FirstName observable of each item. Return a copy of the array (slice(0)) that is sorted (don't want to sort the real array).
Sample here: http://jsfiddle.net/rniemeyer/93Z8N/
Note regarding Knockout Version 2.0 and greater: ko.dependentObservable is now ko.computed. See Dependent Observables
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