Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an observableArray for one of the templates

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?

like image 405
Andrey Avatar asked Aug 06 '11 09:08

Andrey


1 Answers

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

like image 111
RP Niemeyer Avatar answered Oct 13 '22 18:10

RP Niemeyer