14

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?

1 Answer 1

34

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tnx, RP Niemeyer. This is what I wanted:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.