Use Meteor with Node. js to compile a real-time chat application example, meteornode. js
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. <! -- More --> 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)
$ curl https://install.meteor.com | / bin / sh
Metror will do it himself and install command line tools.
To create a new project, first go to your working directory and run the code below. This will create a directory, which includes Meteor and a basic template program.
$ meteor create chat
Now, you can go to that 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 outdated browser
If you want, you can use Meteor's built-in meteor deploy command to deploy your application to Meteor's own server
$ meteor deploy my-app-name.meteor.com
As long as you update and save your code, all connected browsers will update their pages in real time.
Develop chat application
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 a .meteor folder. This folder contains Meteor itself and MongoDB data files.
In the root folder of your App, you should see these three files: chat.html, chat.css and chat.js. All three files are self-explanatory. The HTML file contains the App's model and appearance, which are all defined by chat.css. The Javascript file contains the script to be executed on the client and server. It is important not to put anything into this script file, such as configuration parameters and passwords, because anyone can see these by looking at 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 simple and has a variety of mouse status prompts.
You can view the following piece of 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 , is available in 'this' if (typeof console! == 'undefined') console.log ("You pressed the button");}};} if (Meteor.is_server) {Meteor.startup (function () {/ / code to run on server at startup});}
Pay attention to the two parts of Meteor.is_client and Meteor.is_server in the if paragraph in Meteor.js. The code in these blocks will be executed separately. When the machine that runs this code is the client, only the code in the clint block will run, and the server is the same. This illustrates the code sharing capabilities of Meteor in practical use.
Delete all the Meteor.is_client and Meteor.is_server code in the if, and only one section remains:
if (Meteor.is_client) {}
Note that after you save the script file, your browser will immediately refresh and load this new code.
Create View
Before we officially start working on this script file, we need to create a new view to display the chat history. Open chat.html in the editor and delete the code inside the body tag. Including the template tag named hello. Only the following parts are left
<head>
<title> chat </ title>
</ head>
<body>
</ body>
Then add the following sentence in the body tag
{{> entryfield}}
The template system used by Meteor is very similar to Mustache. Curly brackets {% raw%} {{}} {% endraw%} indicate the content to be rendered. By simply adding content such as {% raw%} { {hello}} {% endraw%}, the template system will replace it with the value of the hello variable. It will be described in more detail later.
Notice that there is a greater-than sign before 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, that is, the name of the template. This is the template we want to render. Note that the name of the template must be the same as the name of the template specified by the code in the body ({{> entryfield}})
Check the browser, you will find that the page has been refreshed, and the input box has been presented.
Next, add another mutache tag in the body to render the message list
{{> messages}}
Finally, we also 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 using each loop, the context will change. When referencing a variable, you actually refer to the value of each array element.
For example, in our chat application, we traverse each element in the array template "messages", the array can look like
[
{
"name": "Andrew",
"message": "Hello world!"
},
{
"name": "Bob",
"message": "Hey, Andrew!" "
}
]
Then, in each loop, you can see {% raw%} {{message}} {% endraw%} {% raw%} {{name}} {% endraw%}, which will refer to each array element ’s Value instead (Andrew and Bob replace name, and their respective greetings.)
When you return to your browser, you can't see any changes. Because the message array has not been sent to the template, Meteor can't traverse anything to render.
Your chat.html should end up like this
<head>
<title> chat </ title>
</ head>
<body>
{{> entryfield}}
{{> messages}}
</ body>
<template name = "entryfield">
<input type = "text" id = "name" placeholder = "Name" /> <input type = "text" id = "message" placeholder = "Your Message" />
</ template>
<template name = "messages">
<p>
{{#each messages}}
<strong> {{name}} </ strong>-{{message}} <br/>
{{/ each}}
</ p>
</ template>
Javascript
From now on, most of the code we deal with is client code, so unless otherwise stated, the following code is in the if (Meteor.is_client) code block.
Before we write the code that displays the message, let's create a new Collection. Essentially, this is a set of Models. In other words, in the context of this chat application, the Messages collection stores the entire chat history, and each The 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, we wrote it outside the client code block.
Since Meteor does most of the work for us, it is very easy to show the chat history. Just add the following code to the if statement
Template.messages.messages = function () {
return Messages.find ({}, {sort: {time: -1}});
}
Let's take it apart and analyze this code:
Template.messages.messages = function () {…}
The first part of Template indicates that we are modifying the behavior of a template.
Template.messages.messages = function () {…}
The second part of the message is the name of the template, indicating which template is being modified. For example, if we want to do something with the "entryfield" template, just change the code to
Template.entryfields.variable = function () {…}
(Here, please don't do this)
Template.messages.messages = function () {…}
The messages in the third part represent a variable in this template. Remember that our each loop traverses messages? This is the message.
When you open the browser, the page still does not change. This is expected, because we only grab the information, not display it.
At this point, your chat.js should look like this. Are you surprised? Just write some code on the server and we can show a real-time chat recording application.
Messages = new Meteor.Collection ('messages');
if (Meteor.is_client) {
Template.messages.messages = function () {
return Messages.find ({}, {sort: {time: -1}});
}
}
Add Message to the console
This part of the content is optional, of course, it helps you debug the program. You can skip directly to learn how to create a form in response 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 as follows:
Messages.insert ({name: 'Andrew', message: 'Hello world!', Time: 0})
This will create a new record in the database. If the correct operation is performed, the browser will immediately update this message on the page.
Message form
Back in the chat.js file, we will link the input form and the database to receive the submission of user chat data. Add the following code at the bottom, but pay attention to the if statement block.
Template.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 is a lot of code, let's review it again. You may remember that the second word after Template determines which template we are modifying. However, the difference is that the code we wrote is used to bind the database and the messages template. The template we are modifying is entryfield.
The attributes of events in this template include an object, and the attributes of events are presented in the following format:
"[eventname] [selector]"
For example, if we want to bind a click event to a button with ID hello, we will add the following code to the event structure.
"click #hello": function (event) {…}
In our example, we bound a function to a keydown event with ID "message". If you remember, this code was already set when we created the template in the chat.html file.
In the event object, each key has a function as its value. This function is executed when the event is called, where 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 field with ID "message" is pressed (keydown).
The code inside the function is quite simple. First, we check whether the Enter key is pressed (the key code of 13 is entered). Second, we get the DOM elements of the two input fields by ID. Third, we check and ensure that the input value is not empty to prevent users from submitting an empty name or message.
It is important to note the code below. This code inserts the 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 a hard-coded value, we used the value of the DOM element. In addition, we have added the current time to ensure that the chat logs are correctly sorted by time.
Finally, we simply set the two input values to '' to clear the input field.
Now, if you enter the browser, you can try to enter a name and information into the two input fields. After pressing Enter, the input field will be cleared and a new message will appear directly 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. No need to write a line of code that explicitly updates the message log, the new information is displayed and synchronized to multiple browsers and clients.
to sum up
Although Meteor works very cool, and there are some very useful applications to support it, such as Derby.js, but it is immature. An example of this is to browse the document and look for red quotations. For example, the document makes the following statement about the MongoDB collection:
The client is currently given full write access to the collection. They can execute any update command. Once we establish authentication, you will be able to restrict the client's direct insertion, update, and deletion. We are also considering validators or other ORM-like functions.
Any user with full write access is a very big problem, because for any app product-if a user has write access to your entire database, this is a considerable security issue.
It's exciting to see which direction Meteor (and Derby.js!) Is heading in, but unless it matures, it may not be the best choice for a production-level application. Looking forward to the 11 million US dollars of funds can be well utilized.