1

I'm trying to sort users by online property:

var userViewModel = function(data){
    var self = this;
    self.name = ko.observable(data.name);
    self.online = ko.observable(data.online);
};

var mainViewModel = function(data){
    var self = this;
    self.users = ko.observableArray(data.users.map(function(user){
        var model = new userViewModel(user);
        model.online.subscribe(function(){
            self.users.sort(function (a, b) { return b.online() - a.online(); });
        });
        return model;
    }));

    self.users.subscribe(function(){
        console.log('users have changed');
    });
};

HTML:

<div data-bind="foreach: users">
    Online: <div data-bind="text: online"></div>
    <div data-bind="text: name"></div>
</div>

Everything is working fine, but when changing online property, users are sorted and "users have changed" is logged. I understand it happens because I'm changing original array. What I want is - not to change original array, just display it sorted (like angular does it)

3
  • Use filter not sort. i guess if you use filter u ll get separate array with only logged in users. Commented Oct 17, 2013 at 8:29
  • I don't need only logged users, I need all, but sorted. Commented Oct 17, 2013 at 8:31
  • Yes so make two arrays one offline and one online. filter them accordingly so you ll get all of them sorted in 2 different arrays which ll give you ability to perform some actions on a particular set and also if someone goes offline then u just need to remove the element and put it in offline array and vice versa. Commented Oct 17, 2013 at 8:34

1 Answer 1

1

Just create a new computed that populates a sorted list of user.

var mainViewModel = function(data){
    var self = this;
    self.users = ko.observableArray(data.users.map(function(user){
        var model = new userViewModel(user);
        return model;
    }));
    self.sortedUsers = ko.computed(function(){
        var users = self.users();       
        users.sort(function (a, b) { return b.online() - a.online(); });       
        return users;
    });   
};

I hope it helps.

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

Comments

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.