André Varandas
André Varandas

Reputation: 87

Meteor collection sorting not working as expected

I'm trying to sort one collection when the user clicks on a button. It works as expected the first time I click, but then when I click it again nothing happens.

On meteor.startup i'm sorting my collection by 'date'. When the user clicks the category button, it changes the sort by to 'category', and then I am trying to handle each click that same button, to change the sort from ascending to descending.

Heres the snippet that handles the user click:

(I'm almost sure the problem is somewhere here)

layout.js

Template.layout.events({
'click #cat': function(event) {
    event.preventDefault();

    //sets the session to a variable
    var sortBy = Session.get('sort_by');

    if (sortBy.category == 'desc') {
        return Session.set('sort_by', {
            category: 'asc'
        });
    } else {
        return Session.set('sort_by', {
            category: 'desc'
        });
    }
  }
})

This is my router.js:

Router.configure({
layoutTemplate: 'layout',
waitOn: function() {
    return Estagios.find({},{ sort: Session.get("sort_by")});
  },
})

Publications.js

Meteor.publish('nestagios', function() {
  return Estagios.find({});
})

This is my main.js

Meteor.startup(function() {
Session.set("sort_by", {
    date: -1,
   });
});

Can anyone help me find out, what is wrong here? Thank you.

Upvotes: 1

Views: 144

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20226

Since you're just toggling the direction of the sort you can simplify your event handler down to:

Template.layout.events({
  'click #cat': function(event) {
    event.preventDefault();
    Session.set('sort_by',{category: -Session.get('sort_by').category});
});

The session variable will evaluate to either {category: 1} or {category: -1}

Upvotes: 1

Oliver
Oliver

Reputation: 1380

In your router you should use $orderBy and not sort

Router.configure({
layoutTemplate: 'layout',
waitOn: function() {
    return Estagios.find({},{ $orderBy: Session.get("sort_by")});
  },
})

Upvotes: 0

Related Questions