Use meteor with Node.js to write examples of real-time chat applications _node.js

Source: Internet
Author: User
Tags bind mongodb mongodb collection

I've often seen frames that are compared to derby.js as meteor.js. Like Derby, it can also update views in real time under multiple clients, although it may be a bit different from Derby. Derby makes it easier to use multiple databases, while Meteor is only close to MongoDB. In fact, the API for accessing the database via a mongoose client is very close to what you expect at the server.

While Meteor is now a somewhat flawed and controversial framework, Meteor seems to be a very interesting choice to build applications that have real-time requirements. The individual still likes derby. The programming style based on the traditional callback is more appealing to me, but the lack of robust documentation and a large developer community behind Derby is certainly a big blow. Maybe it will change over time, but it will be much slower than Meteor because the latter has recently received 11 million dollars in Money. This financial fund ensured the existence of meteor and sustained support. For developers who need a framework for fiscal and development stability, this money will only make meteor more advantageous. <!--more--> today, let's take a look at how to create a real but simple meteor application. In essence, this is a novice guide based on Tom's Vimeo screencast. The biggest difference with Tom's Vimeo screencast is the way it handles events. Instead of copying and pasting a meteor sample, I'll step through my own way to submit a message using the ENTER key. Let's get started.

Create a Meteor application

Derby and Meteor a big bonus they have in common is their own command-line tool. Unlike Derby's built-in NPM tool, which uses node, Meteor uses its own.

At the terminal (Mac OS X and Linux), execute the following command. (Please make sure you have node installed before this)

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

Metror will fix it himself and install command-line tools.

To create a new project, go to your working directory and run the code below. This creates a directory that includes Meteor and a basic template program.

$meteor Create Chat

Now, you can go to the directory and run the following code to make it run

$cdchat $meteor
Running on:http://localhost:3000/

To see this most basic application, you only need to open http://localhost:3000/in any of the outdated browsers

If you want, you can use the Meteor built-in Meteor deploy command to deploy your application to meteor your own server

$meteor Deploy my-app-name.meteor.com

As soon as you update and save your code, all the browsers on the connection will update their pages in real time.

Developing chat applications

You can see different files in the folder generated by the meteor create command. If you know how to view hidden files, you can also see a. Meteor this folder. This folder contains the meteor itself, as well as the MongoDB data file.

In your app's root folder, you should be able to see these three files: chat.html, Chat.css, and Chat.js. These three documents are all in their own explanatory parts. HTML files contain the model and appearance of the app, and they are all defined by CHAT.CSS. The JavaScript file contains scripts to be executed on the client and server side. It's important not to put anything into this script file, such as configuration parameters and passwords, because anyone can see that by looking at your application's code.

Open the Chat.js file with your favorite text-editing software. Personally, I like to use sublime Text2, because the tool is concise and many mouse status prompts.

You can view the following code in the Chat.js file:

if (meteor.is_client) {Template.hello.greeting = function () {return ' Welcome to chat. '}; Template.hello.events = {' Click input ': function () {//Template data, if any, are available in ' this ' if (typeof Consol E!== ' undefined ') console.log ("You pressed the button"); } }; } if (Meteor.is_server) {Meteor.startup (function () {//code to run on server at startup});

Note the two parts of Meteor.is_client and meteor.is_server in the if paragraph in the meteor.js. The code in these blocks is executed separately, and when the machine running this code is the client side, only the code in the Clint block is run, and so does the server. This shows that meteor in the actual use of the code sharing ability.

Delete all the meteor.is_client and meteor.is_server segments in the If, and the last one is left:

if (meteor.is_client) {}

Note that when you save the script file, your browser will immediately refresh the new code to load it.

Create Views (view)

Before we get to the formal start of this script, we need to create a new view to show the chat record. Open the chat.html in the editor and delete the code inside the body tag. Include the template label named Hello. Leave only the following sections

 
 

Then add the following sentence to the body tag.

{{> Entryfield}}

Meteor uses a template system similar to mustache. Curly braces {% raw%}{{}}{% Endraw%} represent the content to render. By simply adding content in two pairs of braces, such as {% raw%}{{hello}}{% endraw%}, the template system replaces it with the value of the variable hello. The following will be described in more detail.

Notice that there is a greater than > in front of the word Entryfield? Use this symbol to specify which template to render.

<template name= "Entryfield" >
  <input type= "text" id= "name" placeholder= "name"/> <input type= "text" id= "message" placeholder= "Your message"/>
</template>

In this example, the template tag has a single attribute, the name of the template, which is the template we want to render, notice that the name of the template is the same as the template name specified in the Body code ({{> Entryfield})


View the browser, you will find that the page has been refreshed, the input box has been presented.

Next, add another mutache tag inside the body to render the message list.

{{> Messages}}

Finally, we need to create a new template called messages. Add the following code below the Entryfield template

<template name= "Messages" >
  <p>
    {{#each messages}}
      <strong>{{name}}</strong>- {{message}}
    {{/each}}}
  </p>
</template>

Note the each clause. In meteor you can use the following syntax to traverse an array template

{{{#each [name of Array]}}
{{/each}}}

When you use each loop, the context changes. When referring to a variable, you actually refer to the value of each array element.

For example, in our chat application, we iterate through each element of the array template "messages", which can be as follows,

[
  {
    ' name ': ' Andrew ',
    ' message ': ' Hello world! '
  },
  {
    ' name ': ' Bob ',
    ' message ': ' Hey, Andrew! ""
  }
]

Then, in each loop, you can see {% raw%}{{message}}{% Endraw%}{% raw%}{{name}}{% endraw%}, which references the value of each array element instead (Andrew and Bob replace name, As well as their respective greeting messages.)

When you return to your browser, you don't see any changes. Because the array of messages has not been transmitted to the template, meteor traverses nothing to render.

Your chat.html should end up like this.

 
 


Javascript

From now on, most of the code we handle is client-side code, so unless specifically stated, the following code is in the IF (meteor.is_client) code block.

Before we write the code to show the message, let's start with a new collection. In essence, this is a group of models. In other words, in this chat application environment, Messages Collection holds the entire chat record, and each message record is a model.

Before the If statement, add the following code to initialize the collection:

Messages = new Meteor.collection (' Messages ');

Because we want this collection to be created on the client and server side, we write it out of the client code block.

Since Meteor has done most of the work for us, it is very easy to show the chat record. Just add the following code to the IF statement.

Template.messages.messages = function () {return
  messages.find ({}, {sort: {time:-1}}});


Let's take it apart to analyze the code:

Template.messages.messages = function () {...}

The first part template that we are modifying the behavior of a template.

Template.messages.messages = function () {...}

The second part of the messages is the name of the template that indicates which template is being modified. For example, if we want to do something with the "Entryfield" template, just change the code to

 
 

(Here, please don't do this)

Template.messages.messages = function () {...}

The third part of this messages represents a variable in this template. Remember our each loop traversal messages? This is the mesaages.

When you open the browser, the page still does not change. This is expected because we only crawl the message and not show it.

At this point, your chat.js should be like this. If you're surprised, just write all the code on the server and we can show you a real-time chat log application.

Messages = new Meteor.collection (' Messages ');

if (meteor.is_client) {
 Template.messages.messages = function () {return
  messages.find ({}, {sort: {time:-1}});
 }
}


Add message to console


This part of the content is optional, of course it helps you debug the program. You can just skip down and learn to create a form to respond to keyboard events (key press).

If you want to test your message display code, you can manually insert a record into the database. Open your browser console and enter the following:

Messages.insert ({name: ' Andrew ', message: ' Hello world! ', time:0})

This will create a new record in the database, and the browser will immediately update the message on the page if the correct action is made.

Message form

Back in the Chat.js file, we will link the form and the database for input to receive the user's chat data submission. Add the following code at the bottom, but note that you want to be in the IF statement block.


Template.entryfield.events = {
 "KeyDown #message": function (event) {
  if (Event.which =) {
   //Submit the Form
   var name = document.getElementById (' name ');
   var message = document.getElementById (' message ');
 
   if (name.value!= ' && message.value!= ') {
    Messages.insert ({
     name:name.value, message
     : Message.value,
     Time:Date.now ()
    });
 
    Name.value = ';
    Message.value = ';}}}}

The code is a bit much, let's go over it again. As you may recall, the second word behind the template determines which template we are modifying. But unlike before, the code we write is used to bind databases and messages templates, and the template we're modifying is Entryfield.

The properties of events in this template contain a object,events attribute that is rendered in the following format:


"[eventname] [selector]"
For example, if we want to bind a click event for a button with the ID Hello, we will add the following code to the events structure.

"click #hello": Function (Event) {...}
in our example, we are binding a function to a KeyDown event with ID "message". If you remember, this code was set up long before we created the template in the chat.html file.


In the event object, each key has a function as its value. This function executes when an event is invoked, where the event object is passed as the first argument to the function. In our app, the function is invoked whenever any key is pressed (KeyDown) in an input field with a "message" ID.

The code within the function is fairly straightforward. First, we check to see if the ENTER key is pressed (13 of the critical code is in the input). Second, we get two DOM elements of the input field by ID. Third, we check and make sure that the input value is not NULL to prevent the user from submitting an empty name or message.

Note that the following code is important. This code inserts a message into the database.

Messages.insert ({
 name:name.value,
 message:message.value,
 time:Date.now ()
});

As you can see, this is similar to the code we inserted into the console, but not the hard-coded values, we use the values of the DOM elements. In addition, we added the current time to ensure that the chat log was sorted correctly by time.


Finally, we simply set the value of two inputs to "to empty the input bar."

Now, if you go into the browser, you can try typing a name and information into two input fields. When you press ENTER, the input bar will be cleared and a new message will appear just below your input field. Open another browser window and navigate to the same URL (http://localhost:3000/). Try typing another message, and

As you can see, meteor is very powerful. There is no need to write a line that explicitly updates the message log code, and new information is displayed and synchronized to multiple browsers and clients.

Summarize

Although Meteor works very cool, and there are some very useful applications to support it, such as derby.js, but it is immature. One example of this is to browse the document and look for the red citation. For example, about the MongoDB collection The document makes the following statement:

The client is currently given full write access to the collection. They can perform any update command. Once we have established authentication, you will be able to limit client direct inserts, updates, and deletions. We're also thinking about validators or other similar ORM functions.

Any user with full write access is a big problem because it is a considerable security issue for any app product-if a user has write access to your entire database.

See Meteor (and Derby.js!) It's exciting to move in a direction like this, but unless it matures, it may not be the best choice for a product-level application. Expect that 11 million dollars of money will be well utilized.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.