Meteor leaderboard sample exercise two

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

Exercise 2: Add a button to randomise all players scores

First, let’s add the button to the bottom of the leaderboard template.

<template name="leaderboard">


      <input type="button" class="randomise" value="Randomise" />

The meteor sample already has a formula to generate a random score which is called on startup if the database is empty. So let’s refactor that into a function so that we can reuse it.

var randomScore = function() {
  return Math.floor(Math.random()*10)*5;

// On server startup, create some players if the database is empty.
if (Meteor.is_server) {
  Meteor.startup(function () {
    if (Players.find().count() === 0) {
      var names = ["Ada Lovelace",
                   "Grace Hopper",
                   "Marie Curie",
                   "Carl Friedrich Gauss",
                   "Nikola Tesla",
                   "Claude Shannon"];
      for (var i = 0; i < names.length; i++)
        Players.insert({name: names[i], score: randomScore()});

Now all we need to do is add an event to handle the button click which will do the work: = {


    'click input.randomise': function() {
      Players.find({}).forEach(function(player) {
        Players.update(player, {$set: {score: randomScore()}});

Browse the code at github.


One thought on “Meteor leaderboard sample exercise two

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s