0
votes

If I have setup template helpers in meteor like so:

Template.leaderboard.helpers({
  players: function() {
    return Players.find({}, { sort: { score: -1, name: 1 } });
  });

How can I change the subscription after an event (say a click). For example, how can I reverse the sort after a click event?

1

1 Answers

3
votes

The simplest possible way is to use the global Session object:

Session.setDefault('order', 1);

Template.leaderboard.helpers({
  players: function() {
    return Players.find({}, { sort: { score: Session.get('order'), name: 1 } });
  }
});

Now in your corresponding event hook you can toggle the ordering like this:

Template.leaderboard.events({
  'click': function () {
    Session.set('order', - Session.get('order'));
  }
});

However, if you would rather not use Session, you can also create a reactive state variable in your template instance namespace:

Template.leaderboard.created = function () {
  this.order = new ReactiveVar(1);
}

To access it from within a helper you can use:

Template.instance().order.get()

and in your event hook the template instance will be the second argument (efter event object):

Template.leaderboard.events({
  'click': function (e, t) {
    t.order.set( - t.order.get() );
  }
});

For the above code to work you will probably need to add reactive-var package to your meteor app.