Page 1 of 1

Making a simple live chat using Meteor JS stack Rate Topic: ***** 1 Votes

#1 laytonsdad  Icon User is offline

  • Cheese and Sprinkles
  • member icon

Reputation: 446
  • View blog
  • Posts: 1,907
  • Joined: 30-April 10

Posted 20 January 2014 - 10:41 PM

Getting meteor installed

First make sure your linux machine is up to date and has curl installed.
Then install your local development environment.

curl https://install.meteor.com | /bin/sh

This will get you the latest version of the meteor stack installed on your local machine.

From the help menu "meteor help" we can see our options:

Quote

With no arguments, 'meteor' runs the project in the current
directory in local development mode. You can run it from the root
directory of the project or from any subdirectory.

Use 'meteor create <name>' to create a new Meteor project.

Commands:
run - [default] Run this project in local development mode
create - Create a new project
update - Upgrade this project to the latest version of Meteor
add - Add a package to this project
remove - Remove a package from this project
list - List available packages
bundle - Pack this project up into a tarball
mongo - Connect to the Mongo database for the specified site
deploy - Deploy this project to Meteor
logs - Show logs for specified site
reset - Reset the project state. Erases the local database.
test-packages - Test one or more packages


Now with meteor installed and ready we need to start a new project.
First thing we need to do is navagate to the directory we want to have the project located.
I am choosing to have mine in a folder called meteor_examples on the user desktop of my Ubuntu machine.

cd Desktop/meteor_examples

Now inside of meteor_examples we will create a new meteor application

meteor create chatterbox

You should get a message in your console that looks like this:

Quote

chatterbox: created.

To run your new app:
cd chatterbox
meteor


Now follow the prompt and change to the chatterbox directory and then run your app using "meteor run" or just "meteor".
Now you should see a message like this:

Quote

[[[[[ ~/Desktop/meteor_examples/chatterbox ]]]]]

Initializing mongo database... this may take a moment.


and then when the database is complete and the server is ready you will get a message that you are being hosted at http://localhost:3000
Go there and see your app.

There is a button that you see that logs the number of clicks if you are interested see our development console for your browser.

Congrats you have a working meteor app.


Getting into the application

Now that you have a working application it is time to build our own.
In the folder chatterbox are three visable files and some hidden ones, for now we only want to focus on the three available.

Open chatterbox.css, chatterbox.js, and chatterbox.html in your editor and have a look at what you see. You will see an HTML
file that contains some handlebars templateing code. You see a css file that is empty, and a Javascript file that contains the meat of the application.

Since meteor runs on both the server and the client we have two if statments that check for this "Meteor.isClient()" and "Meteor.isServer()". To keep this
simple we will only be using the client check so you can delete the isServer check for clarity. Then delete all the code inside the isClient block.
This should leave you with just the "if (Meteor.isClient) { }" empty block in your js file.

Now we will move to the html file.

The first thing I learned when dealing with the meteor stack is that the templates are basic. Don't add a doctype as it is already being added as html5 <!DOCTYPE html>

Now for our chat site set up. The first thing we will do is remove all the markup and start fresh with some templates, head, body, foot.

<head>
  <title>chatterbox</title>
</head>

<body>
  {{> head}}
  {{> body}}
  {{> foot}}
</body>


Now to create the templates that corispond with the template calls seen above:

<template name="head">
  <h1>Hello and welcome to Chatterbox</h1>
  <hr/>
</template>

<template name="body">
  <div id="chatText"></div>
  <br/>
  <input type="text" id="userText"/><button type="button">Send</button>
  <hr/>
</template>

<template name="foot">
  <p>Created by {{creator}} {{year}}</p>
</template>


You will notice that in the foot template we have some handlebars template variables that we will set later in the js section.

Now that our site is marked up its time to give it s bit of style in the chatterbox.css file:

/* CSS declarations go here */
body{
  text-align:center;
}
#chatText{
  margin-right: auto;
  margin-left:auto;
  border: silver solid 1px;
  width: 500px;
  height: 400px;
}


Feel free to design any chat area you would like, we will keep it simple for the example.

Now we get to deal with the main idea for meteor, the javascript.
Open the chatterbox.js file and we will begin by adding the creator and year into the foot section.

Using the object Template we can select the foot template and then the creator variable and set it to a string, I used my username:

Template.foot.creator = "LaytonsDad";


Now we select the foot template and the year variable and set it to a function return:

Template.foot.year = function() {
    var _d = new Date();// Create new date
    return _d.getFullYear();// Return the year to the year variable
  };


Your js file should now look like this:

if (Meteor.isClient) {
  // select the template named foot and set the creator variable to your name
  Template.foot.creator = "LaytonsDad";
  // Select the template named foot and set the year using a function return
  Template.foot.year = function() {
    var _d = new Date();// Create new date
    return _d.getFullYear();// Return the year to the year variable
  };
}


If it does then you are ready to check your application. Make sure you have saved all your files and go to http://localhost:3000. It should now have your
variables filled in the template. Now to move on to the main part of this which is the chat feature.

The first thing we need for the chat is a new collection in the database. In order to do this we will declare it above the isClient check in our
javascript file. The collection name must be a gloabl so we don't use var when naming it but we will make it capital:
Posts = new Meteor.Collection("posts");


Now we have a new database collection named Posts. Since we just created it we will have to create a structure so we know what to insert and what is available
to us. We will need to a userTag, text, postDate. The userTag is the name of the user that posted, the text is the text the user posted, and the postDate
will be the seconds representation of the date for sorting our query for posts. So with this in mind lets create a first post shall we.

In the development console of your browser you will need to type

Posts.insert({"userTag": "laytonsdad", "text": "This is a new post from laytonsdad!", "postDate": Math.floor(Date.now()/1000) });


and press enter this will now be in your collection for the next part of displaying posts.

In order to display the posts we will need to first add a new part to our HTML template. This will be an each loop for our variable that will return the posts.
The each will be:

<div id="chatText">
   {{#each messages}}
     <p><b>{{userTag}}</b> - {{text}}</p>
   {{/each}}
  </div>


and the query will be like:

  Template.body.messages = function(){
    return Posts.find({}, {sort: {postDate: -1}, limit: 10});
  };


Inside the chatText div we create the loop for the messages returned from the query. These will contain the userTag, text, and postDate that will
get injected into the variables in the template.

In the js we are selecting the template body and the messages var to be looped and assigning it the return value of a query for everything in the posts
collection and then sorting it descending with a limit of ten docs returned.

You should now see your post in your application.

Next we will work on setting a userTag in a session for the user from a prompt.

  (function() {
    var state = document.readyState;
    if(state === 'interactive' || state === 'complete') {
        Session.set("userTag", prompt("What is your userTag?") || "Guest"); // Set user session with userTag
    }
    else setTimeout(arguments.callee, 1000);// Recall the state of the Dom loading
  })();


The function above will check the readystate of the DOM and if complete it will prompt for a userTag. If none is given it will assign "Guest"
this would need to be ajusted for checks to see if the session is in use by another client but for this it will work fine.

Now that we have a userTag it is time to get some button events set to check the text and post if it is not blank.

So we want to be able to click the button or click enter so we will make some events:

  Template.body.events = {
    'keyup #userText' : function(e){
       if (e.which === 13){
          addPost();
       }
    },
    'click #sendBtn' : function(e){
       addPost();
    }
  }


This also calls a function called addPost:

  function addPost(){
    var userText = document.getElementById("userText").value;
    if (userText.length > 0){
      Posts.insert({"userTag": Session.get("userTag"), "text": userText, "postDate": Math.floor(Date.now()/1000)});
      document.getElementById("userText").value = "";
    }
  }


This should give you a working chat that can be manipulated any way you wish. Below are the final copies of the files for you to use if you need.

Spoiler


For refrences see docs.meteor.com and for videos see eventedmind.com

This post has been edited by laytonsdad: 23 January 2014 - 04:23 PM


Is This A Good Question/Topic? 1
  • +

Page 1 of 1