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.
leaderboard.html:

<template name="leaderboard">

  ...

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

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:

  Template.leaderboard.events = {

    ...

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

Browse the code at github.

About these ads