This is the second in a x part series about Meteor for beginners.
- Part One – Leaderboard: Add a button to change sort order
- Part Two – Leaderboard: Add a button to randomise players’ scores (this post)
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.
Hi Matt,
Seems to be a slight issue with the code. In Chrome I get a 403. See gist for the code that fixes the randomise button.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gistfile1.txt
hosted with ❤ by GitHub