Example of using Meteor with Node. js to compile real-time chat applications

Source: Internet
Author: User

Example of using Meteor with Node. js to compile real-time chat applications

This article mainly introduces how to use Meteor with Node. js Code example of real-time chat application, Node. as an asynchronous framework, js is used to compile real-time applications. For more information, see

I often see Derby. the framework for js comparison is Meteor. js. similar to Derby, it can also update views in real time on multiple clients, although it may be a little different from Derby. derby can easily use multiple databases, while Meteor is only close to MongoDB. in fact, the API for accessing the database through the Mongoose client is very close to what you expect on the server.

Although meteor is currently a framework with some shortcomings and controversies, it seems very interesting to use Meteor to build applications with real-time requirements. I personally like Derby's traditional callback-based programming method, but behind Derby's strength, it lacks robust documentation and a large developer community, this is undoubtedly a big blow. maybe this will change over time, but it will be much slower than Meteor because the latter has recently received $11 million. this Financial Fund ensures the existence and continuous support of Meteor. for developers who need financial and stable development frameworks, this Fund will only make Meteor more competitive. today, let's take a look at how to create a real but simple Meteor application. essentially, this is a new Guide for Tom-based Vimeo screencast. the biggest difference from Tom's Vimeo screencast is the way to handle events. instead of copying and pasting a Meteor sample code, I will process a message submitted using the Enter key step by step. let's get started.

Create a Meteor Application

Derby and Meteor have their own command line tools. Unlike Derby's built-in npm tool for Node, Meteor uses its own.

Run the following command on the terminal (Mac OS X and Linux)

?

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

Metror will handle it by yourself and install the command line tool.

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

?

1 $ meteor create chat

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

?

1

2 $ cdchat $ meteor

Running on: http: // localhost: 3000/

To see the most basic application, you only need to open http: // localhost: 3000/In any obsolete browser/

You can use Meteor's built-in meteor deploy command to deploy your application to Meteor's own server as long as you want.

?

1 $ meteor deploy my-app-name.meteor.com

As long as your code is updated and saved, all connected browsers will update their pages in real time.

Develop chat applications

In the folder generated by the Meteor Create command, you can see different files. If you know how to view hidden files, you can also see the. meteor folder. This folder contains Meteor itself and MongoDB data files.

In the root directory folder of your App, you can see the three files: chat.html, chat.css, and chat. js. These three files are provided with instructions. The HTML file contains the append model in a non-External manner. All of them are defined by chat.css. The Javascript file contains the scripts to be executed on the client and server. It is important not to put anything into this script file, such as configuring parameters and passwords, because anyone can view the code of your application.

Open the chat. js file with your favorite text editing software. Personally, I like to use Sublime Text2, because this tool is concise and has a variety of mouse status prompts.

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

?

1if (Meteor. is_client) {Template. hello. greeting = function () {return "Welcome to chat. ";}; Template. hello. events = {'click input': function () {// template data, if any, is available in 'others' if (typeof console! = 'Undefined') console. log ("You pressed the button") ;};} if (Meteor. is_server) {Meteor. startup (function () {// code to run on server at startup });}

In Meteor. js, pay attention to the two parts of Meteor. is_client and Meteor. is_server in the if section. The code in these blocks is executed separately. When the machine that runs this code is the client side, only the code in the clint block is run, and the server is the same. This demonstrates the code sharing capability of Meteor in practical use.

Delete the code of all the Meteor. is_client and Meteor. is_server segments in if, and only one segment is left:

?

1if (Meteor. is_client ){}

Note: After you save the script file, your browser will immediately refresh and load the new code.

Create View)

Before starting the script file, we need to create a new view to display chat records. open chat.html in the editor and delete the code in the body tag. includes the template tag named hello. leave only the following parts

?

1

2

3

4

5

6

7

  

  

  

  

Add the following sentence to the body Tag:

?

1 {{> entryfield }}

Meteor uses the same template system as Mustache. braces {% raw % }{{}{% endraw %} indicate the content to be presented. by simply adding content in the braces {% raw %} {hello} {% endraw %}, the template system will replace it with the value of the hello variable. we will introduce it in more detail later.

Have you noticed that there is a greater sign before the word entryfield>? Use this symbol to specify which template to render.

?

1

2

3

In this example, the template tag has a single attribute, that is, the template Name. This is the template to be rendered. Note, the template name must be the same as the Template Name specified by the code in the body ({{> entryfield }})

View the browser and you will find that the page has been refreshed and the input box has been displayed.

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

?

1 {{> messages }}

Finally, we need to create a new template named messages. Add the following code under the entryfield template:

?

1

2

3

4

5

6

7

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

?

1

2 {{# each [name of array]}

{{/ Each }}

When you use an each loop, the context changes. When you reference a variable, you actually reference the value of each array element.

For example, in our chat application, we traverse every element in the array template "messages". This array can be like the following,

?

1

2

3

4

5

6

7

8

9

10 [

{

"Name": "Andrew ",

"Message": "Hello world! "

},

{

"Name": "Bob ",

"Message": "Hey, Andrew! ""

}

]

Then, in the each loop, you can see {% raw % }{{ message }}{% endraw % }{% raw % }{{ name }}{% endraw % }, this will reference the values of each array element to replace (Andrew and Bob replace the name and their greeting information .)

When it is returned to your browser, you cannot see any changes. Because the message array has not been transmitted to the template, Meteor cannot traverse anything to render it.

Your chat.html should last like this.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

  

  

  

{> Entryfield }}

{{> Messages }}

  

  

  

Javascript

From now on, most of the code we process is client code, so unless otherwise stated, the following code is in the if (Meteor. is_client) code block.

Before writing the code for displaying a message, let's create a new Collection. essentially, this is a set of Models. in other words, in this chat application environment, the Messages collection stores the entire chat record, and each message record is a Model.

Before the if statement, add the following code to initialize the Collection:

?

1 Messages = new Meteor. Collection ('messages ');

Because we hope this Collection can be created on the client and server, we have written it out of the client code block.

Since Meteor has done most of the work for us, it is very easy to display chat records. You just need to add the following code to the if statement.

?

1

2

3Template. messages. messages = function (){

Return Messages. find ({},{ sort: {time:-1 }});

}

Let's split and analyze this Code:

?

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

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

?

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

The second part of messages is the Template Name, indicating which template is being modified. For example, if we want to do something about the "entryfield" template, we only need to change the code

?

1Template. entryfields. variable = function (){... }

(Do not do this here)

?

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

The messages in the third part represents a variable in this template. Do you still remember our each loop to traverse messages? This is the mesaages.

When you open the browser, the page remains unchanged. This is expected because we only capture the information and do not display it.

At this time, your chat. js should be like this. If you are surprised, you just need to write such code on the server to display a real-time chat record application.

?

1

2

3

4

5

6

7 Messages = new Meteor. Collection ('messages ');

If (Meteor. is_client ){

Template. messages. messages = function (){

Return Messages. find ({},{ sort: {time:-1 }});

}

}

Add Message in console

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

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

?

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

This will create a new record in the database. If the operation is correct, the browser will immediately update this message on the page.

Message form

Return to the chat. js file and link the form and database for input to receive the submission of user chat data. Add the following code at the bottom, but note that it should be in the if statement block.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20Template. entryfield. events = {

"Keydown # message": function (event ){

If (event. which = 13 ){

// 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 = '';

}

}

}

}

There are a lot of code. Let's review it again. You may remember that the second word after the Template determines which Template we are modifying. However, the code we wrote is used to bind the database and messages template, and the template we are modifying is entryfield.

In this template, the events attribute contains an object. The events attributes are displayed in the following format:

"[Eventname] [selector]"

For example, if we want to bind a click event to a button with the ID of hello, we will add the following code to the structure of events.

"Click # hello": function (event ){... }

In our example, we bind a function to a keydown event with the ID of "message. If you still remember, this code was already set when we created a template in the chat.html file.

In an event object, each key has a function as its value. This function is executed when an event is called. The event object is passed to the function as the first parameter. In our app, this function is called whenever any key in the input column with an ID containing "message" is pressed (keydown.

The code in the function is quite simple. First, check whether the Enter key is pressed (the input contains 13 key code ). Second, we use the ID to obtain the DOM elements in the two input columns. Third, check and ensure that the input value is not empty to prevent users from submitting an empty name or message ).

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

?

1

2

3

4

5Messages. 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 it is not a hard-coded value. We use the value of the DOM element. In addition, the current time is added to ensure that chat logs are correctly sorted by time.

Finally, we set the two input values to ''to clear the input column.

Now, if you enter the browser, you can try to enter a name and information in two input columns. After you press enter, the input column is cleared, and a new message appears at the bottom of your input field. Open another browser window and navigate to the same URL (http: // localhost: 3000 /). Try to enter another information, while

As you can see, Meteor is very powerful. You do not need to write a line of code that explicitly updates the message log. New information is displayed and synchronized to multiple browsers and clients.

Summary

Although Meteor works very cool, and some very useful applications support it, such as Derby. js, It is not mature. An example of this is to browse the document and find the red citation. For example, the document about the MongoDB set is described as follows:

Currently, the client is granted full write access to the set. They can execute arbitrary update commands. Once authentication is established, You can restrict the direct insertion, update, and deletion of the client. We are also considering the validator or other functions similar to ORM.

It is a big problem that any user has full write access permissions, because if a user has write access permissions to your entire database for any app product, this is a big security issue.

See Meteor (and Derby. js !) It is exciting to move in the direction of the image, but unless it is more mature, it may not be the best choice for a product-level application. We look forward to making good use of that $11 million billion.

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.