Rapid Web Application Development With Meteor

FideliaElj 9年前

来自: http://code.tutsplus.com/tutorials/rapid-web-application-development-with-meteor--cms-25130

What You'll Be Creating
</figure>

Meteor provides you with a fast development workflow that will create isomorphic web apps that ‘just work’. The Meteor architecture is truly beautiful in that it will update all clients connected to your app simultaneously, straight out of the box. This has huge implications for creating reactive web apps.

Installing Meteor

Meteor is built with ease of use in mind, and thankfully this philosophy is carried right through from the very start.

Installation is as simple as running the following command on Linux / Mac OS X systems:

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

Windows users can download the official installer .

Creating Your App

This is done at the command line via the meteor tool. To create a new app named my_meteor_app in your home directory, do the following:

$ meteor create ~/my_meteor_app  $ cd ~/my_meteor_app  $ meteor

You will now be able to access your meteor app via http://localhost:3000—port 3000 is the default.

File Structure

By default you will have the following files created:

~/my_meteor_app:  ├── my_meteor_app.css  ├── my_meteor_app.html  └── my_meteor_app.js

The my_meteor_app.html file contains the markup required to display the page—Meteor uses a handlebar curly-brackets style syntax. All of the code in your HTML files is compiled with Meteor’s Spacebars compiler. Spacebars uses statements surrounded by double curly braces such as {{#each}} and {{#if}} to let you add logic and data to your views.

You can pass data into templates from your JavaScript code by defining helpers, and to iterate arrays we can use {{#each items}} .

The my_meteor_app.js file contains both the JavaScript required to start the client, and the server. Any events for the client or directives can be specified in this file.

The css file is for styling your app, and by default is blank.

How the HTML Files Work

Meteor parses all of the HTML files in your app folder and identifies three top-level tags: <head> , <body> , and <template> .

Everything inside any <head> tags is added to the head section of the HTML sent to the client, and everything inside <body> tags is added to the body section, just like in a regular HTML file.

Everything inside <template> tags is compiled into Meteor templates, which can be included inside HTML with {{> templateName}} or referenced in your JavaScript with Template.templateName .

A Working Example

Replace the default HTML with the following:

<head>    <title>My Todo List</title>  </head>     <body>    <div class="container">      <header>        <h1>My Todo List</h1>        <p>Built Using Meteor Framework!</p>      </header>         <ul>        {{#each tasks}}          {{> task}}        {{/each}}      </ul>          </div>  </body>     <template name="task-item">    <li>{{text}}</li>  </template>

Here we specify a template and {{#each}} loop to create a bullet-point list. Finish the example by adding to the my_meteor_app.js :

if (Meteor.isClient) {    // Code here only runs on the client    // Assign some tasks to populate your data    Template.body.helpers({      tasks: [        { text: "Plant cucumbers in fresh manure" },        { text: "Move avocados to larger pots" },        { text: "Go Fishing with Ben" },        { text: "Take the wife to yoga" },        { text: "Cancel tv subscription" }      ]    });  }

Take a look in your browser at the finished result. We can now take things further by implementing persistent data with a MongoDB collection.

Persistent Data With MongoDB

Meteor makes working with data easy. With collections, the data is available in any part of your code as it can be accessed by both the client and the server. This makes it very easy to write some view logic and have the page update itself automatically.

In Meteor, any view components that are linked to a data collection will automatically display the latest changes to the data, so it is reactive in real time.

Change your my_meteor_app.js file to utilise MongoDB with the following:

Tasks = new Mongo.Collection("tasks");     if (Meteor.isClient) {    // This code only runs on the client    Template.body.helpers({      tasks: function () {        return Tasks.find({});      }    });  }

The line Tasks = new Mongo.Collection("tasks"); tells Meteor to set up a MongoDB collection named tasks . The repercussion for this in Meteor is that on the client it creates a cached connection to the server collection.

To insert data we can use the servers console. To start it from a new terminal window, cd into your app’s directory and run (this must be done whilst meteor is running in a separate tab):

$ meteor mongo

Now, inside the console for your app’s Mongo DB, add a record with:

db.tasks.insert({ text: "New task from mongo!", createdAt: new Date() });

Take a look inside the browser now to see the updates. Open up developer tools and in the console run the following:

Tasks.insert({ text: "straight to mongo from console", createdAt: new Date() });

Your list will now update dynamically on the screen. Open a separate browser window in a new instance on your desktop. Run another insert into the console.

You will see both instances update in real time without having to refresh the page. Imagine the implications now of updating the database and Meteor updating all clients.

This is why Meteor is easy for creating a truly reactive app experience. Users will be able to see data updating in real time collaboratively in the browser.

Meteor Packages

The meteor project has a public package server of isobuild packages. This enables you to quickly add functionality to your Meteor app simply by installing a package via the meteor add <package name> syntax.

Adding npm Packages

Meteor can also add npm packages via the meteor add <package name> syntax. Let’s make our display a little nicer in our previous example by adding the moments package for easy date formatting.

$ meteor add momentjs:moment

Now that you have moment available in your app, you can just use it. You do not need to do any including yourself.

Edit the template HTML like so:

<head>    <title>My Todo List</title>  </head>    <body>    <div class="container">      <header>        <h1>My Todo List</h1>      </header>        {{> todo}}      </div>  </body>    <template name="todo">    <ul>      {{#each tasks}}        <li>{{text}} {{createdAt}}</li>      {{/each}}    </ul>  </template>

Now we update our helper functions in the my_meteor_app.js file:

Tasks = new Mongo.Collection("tasks");    if (Meteor.isClient) {    // This code only runs on the client    Template.todo.helpers({      tasks: function () {        return Tasks.find({});      },      createdAt: function () {        return moment(this.createdAt).fromNow();      }    });  }

Switch to your browser window, and as long as the meteor command is still running in the terminal you will see your updated list with moments providing the time measurement. Nice!

OAuth

Adding OAuth authentication to your app is now really simple. It can be achieved by just adding two packages via the following command:

$ meteor add accounts-google  $ meteor add accounts-ui

Once these packages are added to your app, you can simply add the {{> loginButtons}} built-in template to your my_meteor_app.html file. Reloading in a browser you will see a button to configure the Google login feature. Follow the steps provided and you’re ready to go—it’s that easy.

Conclusion

Meteor is a fantastic framework that is gaining more and more popularity, and I believe it’s easy to see why, due to the simple design and implementation of packages. Rapidly prototyping apps in a week is no big deal when you have Meteor in your toolbox.

If you would like to learn more about Meteor, continue reading online with their excellent documentation .

</div>