A place to breathe

Tuesday, June 10, 2014

Meteor Template

You can think of a template as a "app block" that you are going to implement. For example, I want to define a "leaderboard" app block in my website. The cool thing is you can even have app block within an app block.

In a typical meteor example, let's say you want to create a leaderboard for a game. You have a name, score, and a simple button that can increase the score of each an individual person in the list:


name1    score 
name2    score 
… 
button 

In a non-meteor app, you need to first create a form, and post a "request" to the server. Sounds familiar?

In meteor, what we do is we lump both client and server code in one leaderboard.js, and use the "Template" class to make changes to our app.

In our html code, we put the following:

{{> leaderboard}}

This means that there's a template called "leaderboard" that has been created and accessible by the client.

You create the template by defining the following in the HTML:



 

    {{#each players}}
      {{> player}}
    {{/each}}
 

  {{#if selected_name}}
 

   
{{selected_name}}

   
 
  {{else}}
 
Click a player to select

  {{/if}}



In our leaderboard.js. we access the leaderboard template like the following:

  Template.leaderboard.selected_name = function () {
    var player = Players.findOne(Session.get("selected_player"));
    return player && player.name;
  };

"Players" is a class that is instantiated using the MongoDB package like this:

Players = new Meteor.Collection("players");

We initialize all the names in the server code:

if (Meteor.isServer) {
  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: Math.floor(Random.fraction()*10)*5});
    }
  });

No comments:

About Me

I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.