Adding games

Adding games will be similar to adding teams. We'll use a helper called 'isCreatingGame' that changes the template to include a form when active. It will use the reactive source Session to do this.

client/views/games.html

<template name="games">
  <h3>Games</h3>
  {{#if isCreatingGame}}
    <form class="form-create">
      <select name="teamOne">
        {{#each teams}}
          <option value="{{_id}}">{{name}}</option>
        {{/each}}
      </select>

      vs

      <select name="teamTwo">
        {{#each teams}}
          <option value="{{_id}}">{{name}}</option>
        {{/each}}
      </select>

      <button type="submit">Submit</button>
      <a class="cancel" href="#">Cancel</a>
    </form>
  {{else}}
    <a class="create" href="#">Create</a>
  {{/if}}

  <ul>
    {{#each games}}
      {{> game}}
    {{/each}}
  </ul>
</template>

client/views/games.js

Template.games.helpers({
  games: function(){
    return Games.find();
  },

  teams: function(){
    return Teams.find();
  },

  isCreatingGame: function(){
    return Session.get('isCreatingGame');
  }
});


Template.games.events({
  "click a.create": function(e, tpl){
    e.preventDefault();
    Session.set('isCreatingGame', true);
  },

  "click a.cancel": function(e, tpl){
    e.preventDefault();
    Session.set('isCreatingGame', false);
  },

  "submit form.form-create": function(e, tpl){
    e.preventDefault();

    var team1 = {
      _id: tpl.$("select[name=teamOne]").val(),
      name: tpl.$("select[name=teamOne] option:selected").text(),
      score: 0
    }

    var team2 = {
      _id: tpl.$("select[name=teamTwo]").val(),
      name: tpl.$("select[name=teamTwo] option:selected").text(),
      score: 0
    }

    var game = {
      createdAt: new Date(),
      teams: [team1, team2],
      completed: false
    }

    var gameId = Games.insert(game);

    // Add this game to both teams gameIds
    Teams.update({_id: team1._id}, {$addToSet: { gameIds: gameId}});
    Teams.update({_id: team2._id}, {$addToSet: { gameIds: gameId}});

    Session.set('isCreatingGame', false);
  }
});

Creating a game

The "submit form.form-create" event handler is a big one here. However most of it is stuff we've covered, so it should make sense. Remember you can check your created data in three ways:

  • Mongol by hitting ctrl-m
  • Browser console with commands like Games.find().fetch()
  • Mongo command line with meteor mongo and running commands like db.games.find()