Day 15:meteor--Create a Web app from scratch

Source: Internet
Author: User
Tags documentation epoll mongodb pack chrome developer chrome developer tools

So far we have discussed JavaScript technologies such as Bower, AngularJS, Gruntjs, and PhoneGap. Today is the 15th day of the challenge of "30 days of learning 30 new technologies," and I decided to return to JavaScript and learn the meteor framework. Although Meteor's documentation is fairly good, it lacks a tutorial for beginners. I think the tutorial will work better, because tutorials can help you get started with a technology quickly. This article describes how to build a Epoll application using the METEOR framework.
what is meteor.

Meteor is a new generation of open-source frameworks for developing instant Web applications that can help you develop in the least amount of time. Its concept and Angularjs, Backbonejs and other frameworks are very different. When we work on backbone and angular, the client (angular or backbone) communicates with the rest backend. We can write REST backend with any technology, such as Java, NodeJS, PHP.

Meteor uses DDP (Distributed data Protocol) to transfer data between the client and the server. The primary problem that the client-side JavaScript developer needs to address is that the back-end database initiates the query, sends the data to the client, and pushes the changes to the client when the database changes. DDP is the standard way to solve this problem.

The back end of the meteor application is based on node and MongoDB. Both front-end and back-end applications use the Meteor API. Future developers can choose a database other than MongoDB. why use Meteor.

Please read the seven principles of meteor. Application Case

In this article we will build a Epoll app that allows users to post questions and vote. This application can do:

When the user accesses/, you will see a list of issues. Users need to sign in via Twitter to vote or post new questions. As shown in the following illustration, the voting button is not available because you are not logged in.

When the user clicks sign on with Twitter, he will authorize the Epoll app to use his account. After a successful authorization, the user can vote or post a new question.
GitHub Warehouse

The code for today's sample app can be obtained from GitHub. Installing Meteor

Getting started with meteor is easy. If you use Mac or Linux, just enter the following command:

Curl Https://install.meteor.com | /bin/sh

Windows users See document creation Meteor app

It's easy to create meteor apps. Once installed, run the Create command.

Meteor Create Epoll

This creates the Epoll directory, which has some template files under it. The project structure is as follows:

Let's explain this structure:

Meteor folder to save meteor specific files: Gitignore ignores the local folder where MongoDB database files and application files are stored. Packages indicates the package required for this application. You can think of them as NPM packages. Meteor provides functionality in the form of a package. Some packages are used in this article. Release saved the meteor version. The version used in this article is 0.6.6.3.

EPOLL.CSS determines which CSS style to apply.

Epoll.html is the HTML tag of the app. Currently meteor only supports the handlebars template engine, but it may support other template engines in the future.

Epoll.js is the core of meteor applications. Epoll.js is also deployed in both the server segment and the client. This allows developers to write at once and use both ends. The epoll.js template created by Meteor is as follows:

if (meteor.isclient) {
  Template.hello.greeting = function () {
    return "Welcome to Epoll.";
  };

  Template.hello.events ({
    ' click input ': function () {
      //template data, if any, was available in ' this '
      if (typ EOF console!== ' undefined ')
        console.log ("You pressed the button");
    }
  );
if (meteor.isserver) {
  meteor.startup (function () {
    //code to run on server at startup
  });
}

Meteor.isserver and Meteor.isclient differentiate between the server-side and the client's code.

The meteor command can run the app:

CD Epoll
Meteor

The app can be accessed through http://localhost:3000. When you click the button, you can see you pressed the button in Chrome developer tools.

Modify the Welcome section of Epoll.js:

Template.hello.greeting = function () {
    return "the Missing Meteor Tutorial!!!";
  };

Changes are automatically applied and the page is automatically refreshed.
Where's MongoDB?

As mentioned earlier, Meteor uses MongoDB to store data. When we install meteor, it will download the latest version of MongoDB at the same time. We can see that MongoDB is installed in the <user.home>/.meteor directory. Use Ps-ef to find the location where MongoDB is installed.

; Ps-ef|grep MONGO

501  1704  1687   0  2:22pm ttys001    0:09.28/users/shekhargulati/.meteor/ Tools/0b2f28e18b/mongodb/bin/mongod--bind_ip 127.0.0.1--smallfiles--nohttpinterface--port 3002--dbpath/users/ shekhargulati/day15/epoll/.meteor/local/db

On my machine, MongoDB runs on port 3002 to avoid conflicts with other MongoDB that run on port 27017 by default. Intelligent Meteor Package Management

As mentioned earlier, meteor implements functionality in the form of packages. These packages can be used on both the browser and the server. Run the following command to learn all the packages supported by Meteor:

Meteor List

Use the meteor Add and Meteor remove commands to add a delete package. add Twitter Bootstrap pack

We will use Twitter bootstrap as the user interface style.

Meteor Add Bootstrap

Note that the meteor package is not necessarily the latest version. Add a twitter license pack

In our app, users need to be authorized by Twitter first to vote or add questions. Meteor provides a Accounts-ui package to add login components to our app:

Meteor Add Accounts-ui

Then we add the authorization provider. In this app, we use Twitter, but we can actually use Facebook, GitHub, Google, Weibo or meetup.

Meteor Add Accounts-twitter

After adding the package, we need to update the next epoll.html to add the twitter login button:

 

Then adjust the style and add the following code to EPOLL.CSS:

/* CSS declarations go here */
. Login-display-name{color:white}
. login-button{background-color:white}
 # Main {
    padding-top:20px;
}

The app will automatically update and you'll see a page like this:

Now click on Configure Twitter Login and ask us to enter information about the Twitter app:

After the prompts are configured, we can log in using Twitter.

After authorization we can log in to the app. After use, we can log out.

MongoDB creates a new user within the user collection. We can use the MONGO command to connect to the database to view:

; ~/.meteor/tools/0b2f28e18b/mongodb/bin/mongo--port 3002 mongodb shell version:2.4.6 connecting to:127.0.0.1:3002/ Test > Show DBS local 0.03125GB meteor 0.0625GB > Use meteor switched to DB meteor > Show Collections Meteor_ Accounts_loginserviceconfiguration system.indexes users > Db.meteor_accounts_loginServiceConfiguration.find () {" 
    Service ":" Twitter "," Consumerkey ":" XXX "," secret ":" XXX "," _id ":" XXX "} > > > Db.users.find (). Pretty () {
            "Createdat": Isodate ("2013-11-11t18:03:23.488z"), "_id": "XX", "services": {"twitter": { "id": "66993334", "screenname": "Shekhargulati", "Accesstoken": "Xxx-xxx", "ac Cesstokensecret ":" xxx "," Profile_image_url ":" HTTP://PBS.TWIMG.COM/PROFILE_IMAGES/378800000254412405/E4ADCF 8fb7800c3e5f8141c561cb57e4_normal.jpeg "," Profile_image_url_https ":" https://pbs.twimg.com/profile_images/378 800000254412405/e4adcf8fb7800c3e5F8141c561cb57e4_normal.jpeg "," Lang ":" En "}," Resume ": {" Logintokens ": [
                {"token": "XXX", "when": Isodate ("2013-11-11t18:03:23.489z")
 }]}, "Profile": {"name": "Shekhar Gulati"}} >
define the application hierarchy

There is a problem with the template application created by Meteor, and the Epoll.js code for the client and server segments is the same. Anyone can use the browser's development tools to view epoll.js.

If we do not want to send unique server-side code to the client, we can use the client and server directories to separate the code.

CD Epoll
mkdir client Server

Create Epollclient.js and Epollserver.js files in two directories, respectively.

Client/epollclient.js the client code inside the store:

Template.hello.greeting = function () {
    return "the Missing Meteor Tutorial!!!";
};

Template.hello.events ({
    ' click input ': function () {
      //template data, if any, was available in ' this '
      if (typ EOF console!== ' undefined ')
        console.log ("You pressed the button");
    }
);

Server-side code stored in Server/epollserver.js:

Meteor.startup (function () {
    //code to run on server at startup
 });
 '

then delete ' epoll.js ': ' '

sh
rm-f epoll.js
Remove Insecure Package

Each meteor application is preloaded with a insecure package. This application allows the client to implement everything on the database. This is useful for prototyping, but it is often not suitable for production environments.

Meteor Remove insecure
Publishing Issues

Now that we have added a feature, the logged-on user can submit a new question.

 

The addquestion template is rendered only when the user logs on. If the user is logged out, you will not see a text box that adds a new question.

We need to update both the client and server-side code to implement this functionality.

Add in Client/epollclient.js:

Template.addquestion.events ({
    ' click Input.add-question ': Function (event) {
        event.preventdefault ();
        var questiontext = document.getElementById ("Questiontext"). Value;
        Meteor.call ("Addquestion", Questiontext,function (Error, QuestionID) {
          console.log (' Added question with Id: ' +questionid;
        });
        document.getElementById ("Questiontext"). Value = "";

    }
});

In the above code:

We will first bind the click Input event to the Add-question class.

We then block the default click events and get the problem text from the DOM.

Then we call the Meteor server method addquestion. The server is responsible for risky operations such as inserting, updating, and deleting data. The client cannot see the implementation, nor can it modify the data privately.

Now we need to modify the server/epollserver.js. We first define a new collection called questions. Then we'll manipulate the collection. Meteor uses Minimongo as the API interface. See Meteor.Collection.documentation See all the operations supported by Minimongo.

Questions = new Meteor.collection ("Questions");

Meteor.startup (function () {
    //code to run on server at startup
});

Meteor.methods ({
  addquestion:function (questiontext) {
    console.log (' Adding Question ');
    var QuestionID = Questions.insert ({
          ' questiontext ': Questiontext,
          ' Submittedon ': New Date (),
          ' Submittedby ': Meteor.userid ()
      });
    return QuestionID;
  }
});

Now visit our app and submit a new question:

View the data in the next MongoDB

> Db.questions.find (). Pretty ()
{
    "Questiontext": "is Sachin Tendulkar the greatest batsman of all time?", 
   "Submittedon": Isodate ("2013-11-11t18:23:02.541z"),
    "Submittedby": "Jnu6oxoaz2um57rz8",
    "_id": " NhqvgDcZqgZgLdDB7 "
}
List of issues

The next feature we'll implement is the list of issues. Users do not need to log in to see a list of all issues.

In the main Div, add:

{{> Questions}}

Then add the problem Template:

<template name= "questions" >
    

Note that we used unless to make sure that the disabled CSS was applied without the user logging in.

To get all the problems, we need to use the question collection on the client to get all the text. Add the following code to the Client/epollclient.js:

Questions = new Meteor.collection ("Questions");

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.