This is the first in a x part series about Meteor for beginners.


I’ve been trying to get up to speed with Meteor lately. Since I don’t have any experience with nodejs it’s been a challenge. However, Meteor’s documentation is very good so I’m getting there.

I started by looking at the leaderboard sample.

The tutorial suggests making 3 enhancements to the leaderboard sample as an exercise. Here’s my attempt at the first one.

Exercise 1: Add a button to toggle between sorting by score and by name

First let’s add a button to the bottom of the “leaderboard” template

<template name="leaderboard">
  <div class="leaderboard">
    {{#each players}}
      {{> player}}

  {{#if selected_name}}
  <div class="details">
    <div class="name">{{selected_name}}</div>
    <input type="button" class="inc" value="Give 5 points" />

  {{#unless selected_name}}
  <div class="none">Click a player to select</div>

      <input type="button" class="sort" value="Change sorting" />

That there is a Handlebars template with name=”leaderboard”. Notice that it has a {{#each players}}. We’ll get to that in a minute.
Now let’s add javascript to toggle the sort order. We’ll need to save the sort order in the Session, so let’s set its default value at startup.

if (Meteor.is_client) {
  Meteor.startup(function() {
    Session.set("sort_order", {score: -1, name: 1});

{score: -1, name: 1} means sort by score (descending) first, then name.
The {{#each players}} I mentioned earlier calls the Template.leaderboard.players() function, so let’s change that to use the sort order stored in the Session.

  Template.leaderboard.players = function () {
    return Players.find({}, {sort: Session.get("sort_order")});

Now all we need to do is change the sort order stored in the Session whenever the button is clicked. So let’s add an event to the object which is fired when the “Change sorting” button is clicked. = {
    'click': function () {
      Players.update(Session.get("selected_player"), {$inc: {score: 5}});
    'click input.sort': function() {
      var sortOrder = Session.get("sort_order");

      if (Object.keys(sortOrder)[0] == "score") { // sort by score desc
        Session.set("sort_order", { name: 1, score: -1 }); // sort by name
      else {
        Session.set("sort_order", { score: -1, name: 1 }); // sort by score desc

See the code on github.

About these ads