Meteor leaderboard sample exercise three

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

Exercise 3a: Remove a scientist from the leaderboard

This should be easy. First, let’s add a button.

<template name="leaderboard">
  
  ...

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

  ...
</template>

And now the event to fire when the button is clicked:

  Template.leaderboard.events = {
    
    ...

    'click input.delete': function() {
      if (confirm('Are you sure you want to delete the player?')) {
        Players.remove(Session.get("selected_player"));
      }
    }

N.B. the remove() function accepts either a selector i.e. Players.remove({_id: Session.get(“selected_player”)}), or a string (which is the _id) as its first argument.

Exercise 3b: Add a new scientist to the leaderboard

Let’s add a new “addPlayer” template to the html:

<template name="addPlayer">
    <div>
        <div>Add a new player:</div>
        <span class="name">Name:</span>
        <input type="text" id="playerName" />
        <span class="score">Score:</span>
        <input type="text" id="playerScore" />
        <input type="button" class="add" value="Add player" />
    </div>
</template>

And now render it after the leaderboard template:

<body>
  <div id="outer">
    {{> leaderboard}}
    {{> addPlayer}}
  </div>
</body>

And now lets add template event code which will fire when the “Add player” button is clicked:


  Template.player.events = {
    'click': function () {
      Session.set("selected_player", this._id);
    }
  };

  Template.addPlayer.events = {
    'click input.add': function () {
      // todo - add validation
      Players.insert({name: playerName.value, score: Number(playerScore.value)});
    }
  };
}

Browse the code on Github.

About these ads

One thought on “Meteor leaderboard sample exercise three

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s