构建meteor应用程序_从头开始学习Meteor.js:构建一个轮询应用程序

本文介绍了Meteor.js,一个基于Node和MongoDB的全栈平台,它具有内置实时功能和全堆栈React性。通过一个简单的投票应用实例,展示了如何使用Meteor构建实时应用,包括安装、项目结构、数据处理、前端模板和投票功能的实现。文章还提到了Meteor的包管理和部署流程,适合初学者快速上手。
摘要由CSDN通过智能技术生成

构建meteor应用程序

什么是流星? (What is Meteor?)

Meteor.js is an open-source platform built on Node and MongoDB. It's not just a framework, it's more than that.

Meteor.js是基于Node和MongoDB构建的开源平台。 它不仅是一个框架,而且还更多。

Is it comparable to Angular? Angular handles just the frontend parts of application. Meteor is more of a platform than Angular. It is both server and client-side code and handles a lot of the parts of applications that we need to create manually in Angular.

它可与Angular相媲美吗? Angular仅处理应用程序的前端部分。 流星比Angular更像一个平台。 它既是服务器端代码,又是客户端代码,它处理了我们需要在Angular中手动创建的应用程序的许多部分。

We'll be diving into a simple application in this tutorial to show off the benefits and power of Meteor.

在本教程中,我们将深入研究一个简单的应用程序,以展示Meteor的好处和功能。

meteor-homepage

重要须知 (Important Things to Know)

  • Real time built into its core: Meteor handles all of the real-time components so that as soon as you update something in your database, that change is made to all other connected users. Out of the box and very easy to use.

    实时内置在其核心中 :Meteor处理所有实时组件,因此,一旦您更新数据库中的某些内容,便会对所有其他连接的用户进行更改。 开箱即用,非常易于使用。
  • Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary.

    全堆React性 。 在Meteor中,实时是默认设置。 从数据库到模板的所有层均在必要时自动更新。
  • Built-in build system Meteor believes that we spend too much time packaging our applications together and getting all the dependencies working together nicely. You don't have to fiddle with a Gulp configuration anymore. Meteor handles it all for you out of the box.

    内置的构建系统 Meteor认为,我们花费太多时间将应用程序打包在一起,并使所有依赖关系很好地协同工作。 您不必再花时间使用Gulp配置了。 流星开箱即用。
  • Great for single page apps and mobile

    非常适合单页应用程序和移动设备
  • Packages are handled through Meteor's pacakage management site: atmosphere.js (can also use npm and cordova packages)

    是通过流星的pacakage管理现场处理: atmosphere.js (也可以使用NPM和科尔多瓦包)
  • Connecting to external services and APIs is possible using ddp: DDP, the Distributed Data Protocol, is a simple protocol for fetching structured data from a server, and receiving live updates when that data changes. We won't deal with this in our application today, but it's good to know.

    使用ddp可以连接到外部服务和API:DDP(分布式数据协议)是一种简单的协议,用于从服务器获取结构化数据,并在数据更改时接收实时更新。 我们今天不会在我们的应用程序中处理此问题,但是很高兴知道。

我们将要建设的 (What We'll Be Building)

We'll be creating a very simple polling application where a user can:

我们将创建一个非常简单的轮询应用程序,用户可以在其中进行以下操作:

  • Create a poll with 3 choices

    创建具有3个选择的民意测验
  • Vote on polls

    投票表决
  • New polls and votes will show real-time

    新的民意调查和投票将显示实时

View the Demo

观看演示

Let's create our first Meteor app!

让我们创建第一个Meteor应用程序!

入门 (Getting Started)

安装流星 (Install Meteor)

  • download for windows: https://install.meteor.com/windows

    Windows版下载:https://install.meteor.com/windows
  • install for osx/linux: curl https://install.meteor.com/ | sh

    为osx / linux安装:curl https://install.meteor.com/ | SH

install-meteor-windows

  • test to make sure everything is installed (windows users only cmd)

    测试以确保已安装所有组件(仅Windows用户cmd)
meteor --version

meteor-version

演示应用 (Demo Apps)

Meteor comes with a few demo applications that you can try out. If you want to check out a few demo apps now, you can go into your command line and grab the demo application using:

流星附带了一些演示应用程序,您可以尝试。 如果您现在想签出一些演示应用程序,则可以进入命令行并使用以下方法获取演示应用程序:

// todo sample app
meteor create --example todos

// example mobile application
meteor create --example localmarket

You can find the full list of examples in the Meteor GitHub.

您可以在Meteor GitHub中找到示例的完整列表。

Once you create a demo app, just cd into that project and run the application with:

一旦你创建了一个演示应用程序,只是cd转化项目并运行应用程序:

meteor

This will grab the necessary packages, bundle all the css and js, start your application using a Node server, and make it viewable in your browser.

这将获取必要的软件包捆绑所有css和js使用Node服务器启动应用程序 ,并使其在浏览器中可见。

http://localhost:3000

http://本地主机:3000

Here is the sample Todos application which is quite good looking:

这是示例Todos应用程序,看起来很不错:

meteor-demo-todos

Definitely click around the files in these demo applications and you'll see how Meteor apps tick. Let's move onto creating our own application now.

绝对单击这些演示应用程序中的文件,您将看到Meteor应用程序如何打勾。 现在让我们继续创建自己的应用程序。

创建一个新的应用程序 (Create a New Application)

With our newly installed Meteor CLI tools, we can easily create a new application with:

借助我们新安装的Meteor CLI工具,我们可以轻松创建具有以下内容的新应用程序:

meteor create polling

meteor-create-new-app

polling will be the name of our new application and it will be created in a new polling/ folder. This command will create 3 new files and a folder:

polling将是我们新应用程序的名称,它将在新的轮询/文件夹中创建。 此命令将创建3个新文件和一个文件夹:

| .meteor/              // holds information about our project
| polling.css       // the css for our project
| polling.html      // the overall template
| polling.js            // javascript for the client and server

This is a very barebones setup and will not be how we structure our application, but it is useful to see how a very simple application can be built.

这是一个非常准系统的设置,将不会是我们构建应用程序的方式,但是了解如何构建一个非常简单的应用程序会很有用。

You can run this app by cding into your new project and starting your meteor app with:

您可以运行这个程序通过cd ING到您的新项目,并开始与您的流星应用:

meteor

Then you can view it in the browser at http://localhost:3000

然后您可以在浏览器中的http:// localhost:3000上查看它

meteor-new-app-barebones

If you take a quick look into polling.js you'll see some JavaScript bindings to the Template (which is referencing our polling.html file). What you'll also find is two interesting lines of code that are how Meteor separates code that will be run on the server vs the client.

如果快速polling.js您会看到一些到Template JavaScript绑定(引用了我们的polling.html文件)。 您还会发现两条有趣的代码行,它们是Meteor分离将在服务器与客户端上运行的代码的方式。

if (Meteor.isClient) {
    // code here will only be run on the client
}

if (Meteor.isServer) {
    // code here will only be run on the server
}

While we could build our whole application like this, with client and server code in the same file, I prefer to have our application structured so that we don't have to worry about where our client and server code is.

尽管我们可以这样构建整个应用程序,但客户端和服务器代码在同一个文件中,但我更喜欢对应用程序进行结构化,这样我们就不必担心客户端和服务器代码在哪里。

Keep that meteor command running for the duration of this tutorial. As we make changes to our application, Meteor will automatically restart the server, rebundle our files, and livereload our browser (while keeping all our data). Talk about convenient!

在本教程中,请继续运行该meteor命令。 当我们对应用程序进行更改时, Meteor将自动重新启动服务器,重新打包文件,并实时重新加载浏览器(同时保留所有数据) 。 讲方便!

流星推荐的应用程序结构 (Meteor Recommended Application Structure)

Luckily, Meteor has a few folders that are designed specifically for organizing our application. These folders are:

幸运的是,Meteor拥有一些专门用于组织我们的应用程序的文件夹。 这些文件夹是:

  • client/: The client folder is for files that will only be served to the client. Any CSS and JS files in this folder will be automatically bundled and sent to the browser.

    client / :客户端文件夹用于仅将文件提供给客户端的文件。 此文件夹中的所有CSS和JS文件都会自动捆绑并发送到浏览器。
  • server/: The folder for all your server side code. Store sensitive logic or data that a client shouldn't see.

    server / :所有服务器端代码的文件夹。 存储客户不应看到的敏感逻辑或数据。
  • public/: By default, Meteor will find the CSS and JS files in your project and bundle them together. Anything in this public folder will be not be bundled by Meteor and will be served directly to the client as-is. If you have an image at public/images/underwater-dogs.jpg, then you can reference that file from HTML using <img src="images/underwater-dogs.jpg">.

    public / :默认情况下,Meteor将在您的项目中找到CSS和JS文件并将它们捆绑在一起。 该公共文件夹中的任何内容都不会被Meteor捆绑,而是直接按原样提供给客户端。 如果您在public / images / underwater-dogs.jpg上有一张图片,则可以使用<img src="images/underwater-dogs.jpg">从HTML引用该文件。
  • private/: These files are only accessed by the server through the Assets API. We won't be dealing with this folder for this tutorial.

    private / :这些文件只能由服务器通过Assets API进行访问 。 在本教程中,我们将不处理此文件夹。

What's cool is that with this structure, we won't need to defined Meteor.isClient or Meteor.isServer anymore. If a file is in that folder, then Meteor knows which side of our application it belongs.

很棒的是,有了这种结构,我们不再需要定义Meteor.isClientMeteor.isServer 。 如果文件在该文件夹中,则Meteor知道它属于我们应用程序的哪一侧。

With these reserved folders in mind, let's look at how our application structure will look like:

考虑到这些保留的文件夹,让我们看一下我们的应用程序结构如何:

| .meteor
| client/                       // all the code for our client and browser
    |----- components/          // we'll be creating components for our application parts
      |--- poll-form.css
      |--- poll-form.html
      |--- poll-form.js
      |--- poll.css
      |--- poll.html
      |--- poll.js
    |----- app.body.html        // layout for our entire app
    |----- app.head.html        // document head for entire app
    |----- app.js                   // the overall js for our layout
    |----- app.css                   // the overall css for our layout
| collections/              // here we'll store our mongo models
    |----- polls.js         // defining our mongo collection
| server/                       // code for our server
    |----- bootstrap.js // adding sample data on app startup

client/ will be the folder where we spend most of our time. We'll go through all of the components, views, CSS/JS in the next section.

client /将是我们大部分时间的文件夹。 在下一节中,我们将介绍所有组件,视图,CSS / JS。

client/components/ will hold the different parts of our application. In this case, we just need a form to create polls and a component to show the individual polls. All JS and CSS files in the client folder will be bundled together by Meteor into our application so we're naming these files is done however we want. They'll all go to the same place anyway.

客户/组件/将保留我们应用程序的不同部分。 在这种情况下,我们只需要一个用于创建民意测验的表单和一个用于显示各个民意测验的组件。 客户文件夹中的所有JS和CSS文件都将被流星捆绑在一起到我们的应用程序中,因此我们可以根据需要命名这些文件。 无论如何,他们都会去同一个地方。

server/ will only contain one thing for now. We'll create a bootstrap.js file to seed our database with some sample data.

服务器/目前仅包含一件事。 我们将创建一个bootstrap.js文件,为我们的数据库添加一些示例数据。

collections/ is where we define Mongo collections. In this case, we'll only need one called polls.js.

collections /是我们定义Mongo集合的地方。 在这种情况下,我们只需要一个名为polls.js

routes.js will be in the root of our folder since the routes will be used in both the client and the server.

由于路由将同时在客户端和服务器中使用,所以route.js将位于我们文件夹的根目录中。

Take a look at the docs for more on Meteor file structure.

查看有关更多有关Meteor文件结构的文档。

We're going to start with the server and the collections part of our application first.

我们将从应用程序的服务器和集合部分开始。

定义Mongo集合 (Defining a Mongo Collection)

MongoDB is very simple to work with and we've gone over MongoDB in our article: An Introduction to Mongo. For our purpose for this application, we will be defining a single collection. Let's do that now.

MongoDB的使用非常简单,我们已经在文章: Mongo简介中介绍了MongoDB。 为了达到此应用程序的目的,我们将定义一个集合。 现在开始吧。

Create the collections/polls.js file and fill it with:

创建collections / polls.js文件,并填充以下内容:

Polls = new Mongo.Collection('polls');

Easy! The reason we define this in a collections/ folder and not in the client/ or the server/ folder is that this collection will be needed on both the server (creating sample polls) and client (creating new polls).

简单! 我们在collections /文件夹中而不是在client /server /文件夹中定义此原因的原因是,服务器(创建样本民意调查)和客户端(创建新民意调查)都需要此集合。

We are re-using code on the server and client and this is what makes Meteor such a breeze to work with. With the Mongo collection out of the way, let's create some sample data.

我们正在服务器和客户端上重用代码,这就是使Meteor轻而易举地使用的原因。 摆脱了Mongo的收集,让我们创建一些示例数据。

引导我们的应用程序和示例数据 (Bootstrapping Our Application and Sample Data)

Let's create some sample data for our application before we start to create the client-side part of our polling application. In the server/ folder, create a new file called bootstrap.js.

在开始创建轮询应用程序的客户端部分之前,让我们为应用程序创建一些示例数据。 在服务器/文件夹中,创建一个名为bootstrap.js的新文件。

Here is the full commented code for bootstrap.js:

这是bootstrap.js的完整注释代码:

// run this when the meteor app is started
Meteor.startup(function() {

  // if there are no polls available create sample data
  if (Polls.find().count() === 0) {

    // create sample polls
    var samplePolls = [
      {
        question: 'Is Meteor awesome?',
        choices: [
          { text: 'Of course!', votes: 0 },
          { text: 'Eh', votes: 0 },
          { text: 'No. I like plain JS', votes: 0 }
        ]
      },
      {
        question: 'Is CSS3 Flexbox the greatest thing since array_slice(bread)?',
        choices: [
          { text: '100% yes', votes: 0 },
          { text: '200% yes', votes: 0 },
          { text: '300% yes', votes: 0 }
        ]
      }
    ];

    // loop over each sample poll and insert into database
    _.each(samplePolls, function(poll) {
      Polls.insert(poll);
    });

  }

});

We are using the Meteor.startup command to run this code when our server starts up. We're going to check if there are any polls already created in our database and create sample polls if there is nothing in the database.

服务器启动时,我们使用Meteor.startup命令运行此代码。 我们将检查数据库中是否已经创建了任何民意调查,如果数据库中没有任何内容,则创建样本民意调查。

Quick Note: If you ever want to clear what's in your database, just run meteor reset and your application will become a clear slate.

快速说明 :如果您想清除数据库中的内容,只需运行“ meteor reset ,您的应用程序就会变得清晰起来。

meteor-reset

从浏览器检查我们的数据库 (Checking Our Database from the Browser)

Since Meteor implements an instance of Mongo on the client, we are able to run MongoDB commands right in our browser's console. Meteor already restarted our application so that means it should've already ran that bootstrap.js file and created our sample polls.

由于Meteor 在客户端上实现了Mongo的实例,因此我们能够在浏览器的控制台中直接运行MongoDB命令。 Meteor已经重新启动了我们的应用程序,因此这意味着它应该已经运行了bootstrap.js文件并创建了示例民意调查。

Let's go into our browser and see our polls. Go into your browser's console and run the Mongo command to find all the Polls:

让我们进入浏览器,查看我们的民意调查。 进入浏览器的控制台并运行Mongo命令以查找所有Polls

Polls.find().fetch()

You'll see the two polls we created!

您会看到我们创建的两个民意调查!

meteor-browser-console-find

We now have the foundation we need to start building our polling application's frontend. We now have:

现在,我们有了开始构建轮询应用程序前端所需的基础。 我们现在有:

  • A solid Meteor file structure foundation

    坚实的Meteor文件结构基础
  • A Mongo collection to hold our polls

    Mongo收集来举行民意调查
  • Sample data in our database

    我们数据库中的样本数据

Let's move onto the thing that our users will actually see, the UI!

让我们继续我们的用户将实际看到的东西,UI!

前端基础和模板 (Frontend Foundation and Template)

  • app.body.html

    app.body.html
  • app.head.html

    app.head.html
  • app.js

    app.js

  • Meteor will find all references of <head> and <body> and combine whatever it finds to one <head> and <body>. So if you have multiple files that have a <body> or <head>, they will all be compiled into your final document.

    流星将找到<head><body>所有引用,并将找到的所有内容组合到一个<head><body> 。 因此,如果您有多个具有<body><head> ,它们都将被编译成最终文档。

Check the docs for more on Meteor templating.

检查文档以获取有关流星模板的更多信息。

Here is what our app.body.html and app.head.html files will consist of:

这是我们的app.body.htmlapp.head.html文件组成的内容:

client / app.body.html (client/app.body.html)
<body>

  <!-- PULL IN THE POLL CREATION FORM -->
  <div class="container">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
        {{ >pollForm }}
      </div>
    </div>
  </div>  

  <!-- LOOP OVER POLLS AND SHOW EACH -->
  <div class="polls">
      {{ #each polls }}
          {{ >poll }}
      {{ /each }}
  </div>

</body>

{{ >pollForm }} will find a file with <template name="pollForm> within it. We will create this file next. The {{ >templateName }} syntax will be how we pull in different views from our application.

{{> pollForm}}将在其中找到一个带有<template name="pollForm>文件。我们接下来将创建此文件。 {{ >templateName }}语法将是我们从应用程序中提取不同视图的方式。

{{ #each polls }} will loop over the polls object and then show the template named poll. We'll look at how we pull in this polls object from our database soon.

{{#each polls}}将遍历polls对象,然后显示名为poll的模板。 我们将研究如何尽快从数据库中提取此polls对象。

client / app.head.html (client/app.head.html)

Here is the very simple <head> of our app. Meteor will inject all the requirements into this section.

这是我们应用程序的非常简单的 <head> 。 Meteor将把所有需求注入此部分。

<head>
  <meta charset="utf-8">
  <title>My Polling App!</title>

  <!-- CSS IS AUTOMATICALLY BUILT AND LOADED -->
</head>

投票模板 (Poll Templates)

Now that we have the main template down, let's create the two templates that we referenced: pollForm and poll.

现在我们有了主模板,让我们创建引用的两个模板: pollFormpoll

投票表(client / components / poll-form.html) (Poll Form (client/components/poll-form.html))

This will store the form for creating polls:

这将存储用于创建民意调查的表单:

<template name="pollForm">

<form> 
    <div class="form-group">
        <label>Question</label>
        <input type="text" name="question" class="form-control" placeholder="Your Question">
    </div>

    <div class="form-group">
        <label>Choice #1</label>
        <input type="text" name="choice1" class="form-control" placeholder="Choice #1">
    </div>
    <div class="form-group">
        <label>Choice #2</label>
        <input type="text" name="choice2" class="form-control" placeholder="Choice #2">
    </div>
    <div class="form-group">
        <label>Choice #3</label>
        <input type="text" name="choice3" class="form-control" placeholder="Choice #3">
    </div>

    <button type="submit" class="btn btn-lg btn-primary btn-block">Create Poll</button>
</form>

</template>

We'll just limit users to creating 3 options for now to keep things simple. In the future, you could add a plus button that adds an input for choices.

为了使事情变得简单,我们现在仅限制用户创建3个选项。 将来,您可以添加加号按钮,为选择项添加输入。

Here's some quick CSS to style the question group a little differently than the option inputs. We'll place this in poll-form.css.

这是一些快速CSS,其样式与选项输入略有不同。 我们将其放置在poll-form.css

.question-group   {
  margin-bottom:20px;
  background:#EEE;
  padding:20px;
}
.question-group label   {
  font-size:18px;
}

Let's go back to our browser and see what our cool application looks like now.

让我们回到浏览器,看看我们酷的应用程序现在看起来是什么样子。

poll-form

Pretty lackluster so far. This is because none of our Bootstrap classes will work because we never got Bootstrap CSS and added it to our project. We'll handle processing this form and then create our poll template. After that we'll move onto getting Bootstrap.

到目前为止还很乏味。 这是因为我们的Bootstrap类都不起作用,因为我们从未获得过Bootstrap CSS并将其添加到我们的项目中。 我们将处理此表单,然后创建我们的poll模板。 之后,我们将继续获取Bootstrap。

client / components / poll.html (client/components/poll.html)

This will be the poll template for showing off single polls.

这将是用于展示单个民意测验的poll模板。

<template name="poll">

<div class="poll well well-lg" data-id="{{ _id }}">

    <h3>{{ question }}</h3>

    {{ #each indexedArray choices }}
        <a href="#" class="vote btn btn-primary btn-block" data-id="{{ _index }}">
            <span class="votes pull-right">{{ votes }}</span>
            <span class="text">{{ text }}</span>
        </a>
    {{ /each }}

</div>
</template>

We will be displaying the question, choices, votes, and text associated with the poll.

我们将显示与民意调查相关的问题选择投票文本

How do we get these polls to show? In our original app.body.html file, we referenced the polls using {{ #each polls }}. We are also adding in data-id with the _index so that we'll be able to know which question to apply our vote to.

我们如何显示这些民意调查? 在我们原始的app.body.html文件中,我们使用{{ #each polls }}引用了民意{{ #each polls }} 。 我们还在_index添加了data-id ,以便我们能够知道将投票应用于哪个问题。

Let's give our body access to this object from our database now.

现在,让我们的身体从数据库中访问该对象。

We can easily assign variables to our body template by going into our app.js file and creating:

通过进入app.js文件并创建以下内容,我们可以轻松地将变量分配给我们的主体模板:

Template.body.helpers({

  polls: function() {
    return Polls.find();
  }

});

Just like we used the Polls collection earlier, we can use it now to grab all our polls. This will give access to the polls object within our body template.

就像我们之前使用Polls集合一样,我们现在可以使用它来获取所有民意调查。 这将允许访问我们body模板中的polls对象。

Notice we also added an indexedArray to the choices each. This is because we don't inherently have the index when we loop over items in Meteor right now. That will probably change in the future, but it isn't implemented currently because of the reactive nature of the templating engine. Apparently $index in these real-time applications is a harder thing to pull off.

注意,我们还为每个choices添加了indexedArray 。 这是因为当我们现在在Meteor中循环浏览项目时,我们固有地没有索引。 这种情况将来可能会改变,但是由于模板引擎的React性,目前尚未实现。 在这些实时应用程序中,显然$ index很难实现。

We need to create this indexedArray helper so let's go back into app.js and add the following:

我们需要创建这个indexedArray帮助器,让我们回到app.js并添加以下内容:

// adds index to each item
UI.registerHelper('indexedArray', function(context, options) {
  if (context) {
    return context.map(function(item, index) {
      item._index = index;
      return item;
    });
  }
});

Thanks to Jenia Nemzer for the above helper. We now have access to the data-id={{ _index }}. We'll use this when we implement our voting features.

感谢Jenia Nemzer的上述帮助。 现在,我们可以访问data-id={{ _index }} 。 当我们实现投票功能时,将使用此功能。

Now we can see our polls that we created in our bootstrap.js file showing in our application.

现在,我们可以看到在bootstrap.js文件中创建的民意测验显示在应用程序中。

polls-showing

Let's wire up our form now to handle form submission.

让我们现在连接表单以处理表单提交。

处理投票表格 (Processing the Poll Form)

Meteor has a cool way of attaching events and variables to its templates. Currently, we have a pollForm template. Let's go into the poll-form.js file and add event handlers for our form submission.

流星有一种很酷的方式将事件和变量附加到其模板。 当前,我们有一个pollForm模板。 让我们进入poll-form.js文件并为表单提交添加事件处理程序。

client/components/poll-form.js

client/components/poll-form.js

Template.pollForm.events({

  // handle the form submission
  'submit form': function(event) {

    // stop the form from submitting
    event.preventDefault();

    // get the data we need from the form
    var newPoll = {
      question: event.target.question.value,
      choices: [
        {  text: event.target.choice1.value, votes: 0 },
        {  text: event.target.choice2.value, votes: 0 },
        {  text: event.target.choice3.value, votes: 0 }
      ]
    };    

    // create the new poll
    Polls.insert(newPoll);
  }

});

Template.pollForm.events is how we attach events to this specific template. We are defining an event to handle the submit form event.

Template.pollForm.events是我们将事件附加到此特定模板的方式。 我们正在定义一个事件来处理submit form事件。

We can pull data from the form inputs using event.target.{input_name}.value.

我们可以使用event.target。{input_name} .value从表单输入中提取数据。

After we have gotten all the data we need, we are going to insert the new poll into our database using Polls.insert() just like we did in our bootstrap.js file on the server-side of things. Go ahead and use your form to submit data and you'll find that the new poll automatically gets added to the list of polls.

在获得所需的所有数据之后,我们将使用Polls.insert()将新的民意调查插入到数据库中,就像在服务器端的bootstrap.js文件中所做的一样。 继续并使用表单提交数据,您会发现新的民意调查会自动添加到民意调查列表中。

添加投票功能 (Adding Voting Capabilities)

We've added polls to our overall template in app.js, handled processing the poll form in poll-form.js; now we will handle the last action, which is voting in the corresponding JS file, poll.js.

我们在app.js的整体模板中添加了polls并在poll-form.js处理了民意调查表单; 现在,我们将处理最后一个动作,即在相应的JS文件poll.js

Inside of client/components/poll.js, let's attach events to our template:

client/components/poll.js ,让我们将事件附加到模板中:

// attach events to our poll template
Template.poll.events({

  // event to handle clicking a choice
  'click .vote': function(event) {

    // prevent the default behavior
    event.preventDefault();

    // get the parent (poll) id
    var pollID = $(event.currentTarget).parent('.poll').data('id');
    var voteID = $(event.currentTarget).data('id');

    // create the incrementing object so we can add to the corresponding vote
    var voteString = 'choices.' + voteID + '.votes';
    var action = {};
    action[voteString] = 1;

    // increment the number of votes for this choice
    Polls.update(
      { _id: pollID }, 
      { $inc: action }
    );

  }

});

A fun thing we can do to traverse the DOM is to use jQuery to call the current event and then find exactly what we need. To update the vote number for what was just clicked, we will need to get the parent ID of the poll and then the index of what was just clicked.

我们可以遍历DOM的一个有趣的事情是使用jQuery调用当前事件,然后准确地找到我们需要的东西。 要更新刚刚单击的内容的投票号,我们需要获取民意调查的父ID,然后获取刚刚单击的内容的索引。

We will be using MongoDB's $inc operator to add 1 to the vote. Go ahead and click through your application and vote, and you'll see the votes increment.

我们将使用MongoDB的$ inc运算符在表决中加上1。 继续并单击您的应用程序并投票,您将看到投票数增加。

You may also be able to see other users voting in real time!

您还可以实时查看其他用户的投票!

This is some very simple templating here with the built in Meteor features. For future larger projects, we'll probably want to look at a routing solution like iron:router, currently the most popular Meteor package in Atmosphere, Meteor's packages site.

这是内置流星功能的一些非常简单的模板。 对于将来的大型项目,我们可能需要考虑一个路由解决方案,例如iron:router ,这是Meteor的软件包站点Atmosphere中目前最受欢迎的Meteor软件包。

使用来自大气层的流星包裹 (Using Meteor Packages from Atmosphere)

Let's install Bootstrap to get some quick styling for our application. The thing to know about Meteor packages is that you only need to install them to get them to work.

让我们安装Bootstrap以获得我们应用程序的一些快速样式。 关于Meteor软件包的了解是,您只需安装它们即可使它们工作。

Traditionally, to get Bootstrap, you would:

传统上,要获得Bootstrap,您将:

  • Download Bootstrap

    下载Bootstrap
  • Move Bootstrap into your project folders

    将Bootstrap移至项目文件夹
  • Add Bootstrap using a <link> tag in your project's <head>

    在项目的<head>使用<link>标记添加Bootstrap
  • Start using Bootstrap

    开始使用Bootstrap

In Meteor, all you have to do is install Bootstrap and it's automatically applied to your project. Meteor's build system will include the CSS on its own.

在Meteor中,您所要做的就是安装Bootstrap,它会自动应用于您的项目 。 流星的构建系统将单独包含CSS。

Let's install Bootstrap found in Atmosphere.

让我们安装Atmosphere中的Bootstrap。

meteor add twbs:bootstrap

meteor-add-bootstrap

Now, if we go look at our application, we'll see that our styling is there!

现在,如果我们看一下我们的应用程序,就会发现我们的样式在那里!

bootstrap-styled

Note: You could also do things the old fashioned way of grabbing the Bootstrap file and adding it to your public/ folder and then linking to it in the document <head> if you want to go that route.

注意:您也可以采用老式的方式来处理Bootstrap文件,并将其添加到public /文件夹,然后在文档<head>链接到该文件<head>如果要执行此操作)。

更简单CSS (A Little More Simple CSS)

In addition to having Bootstrap, let's add some of our own styles real quick to app.css to get our grid of polls looking a bit better:

除了使用Bootstrap之外,我们还可以快速向app.css添加一些自己的样式,以使民意调查表看起来更好一些:

Let's make our polls use flexbox to make it easier to create a grid of polls.

让我们使民意调查使用flexbox使其更容易创建民意调查网格。

Inside of app.css, let's add some quick styling:

app.css内部,让我们添加一些快速样式:

body  {
  padding-top:50px; 
}
.polls  {
  display:flex;
  flex-flow:row wrap;
  justify-content:center;
}
.poll   {
  width:25%;
  margin:20px;
}

We now have a decent looking application with the basic functionality of a polling application!

现在,我们有了一个外观不错的应用程序,它具有轮询应用程序的基本功能!

bootstrap-custom-styled

生产说明 (Notes for Production)

自动发布 (autopublish)

Since our application is still in development mode, all collections are automatically published from our server and subscribed to on our client. We probably won't want this behavior in our production applications since it doesn't make sense for users of our application to subscribe to EVERY part of our application, even the parts they aren't using at any one time.

由于我们的应用程序仍处于开发模式,因此所有集合都将从我们的服务器自动发布并在我们的客户端上订阅。 我们可能不希望在生产应用程序中出现这种行为,因为对于我们的应用程序用户而言,预订应用程序的每个部分,甚至是他们一次不使用的部分,都没有意义。

It makes more sense to only have a user subscribed to the data that they are seeing at any one time. If you go look into .meteor/packages to see the packages in your Meteor application, you'll see one called autopublish. This will need to be removed and then you'll have to publish and subscribe to data manually in your application.

只让用户订阅他们在任何时候看到的数据更有意义。 如果您查看.meteor / packages来查看Meteor应用程序中的软件包,则会看到一个名为autopublish 。 这将需要删除,然后您必须在应用程序中手动发布和订阅数据。

To remove this package, use:

要删除此软件包,请使用:

meteor remove autopublish

Then you can use Meteor.publish() and Meteor.subscribe().

然后,您可以使用Meteor.publish()Meteor.subscribe()

部署中 (Deploying)

Now we want the whole world to see our super cool new application. We can use Meteor's servers to show off our application.

现在,我们希望全世界看到我们的超酷新应用程序。 我们可以使用Meteor的服务器来展示我们的应用程序。

With one simple command, our entire app will be available online:

通过一个简单的命令,我们的整个应用程序将可以在线使用:

meteor deploy scotch.meteor.com

You can change out the subdomain for anything you like as long as it isn't already taken. We'll explore deploying to your own servers in future articles.

您可以根据需要更改子域,只要它还没有被使用即可。 在以后的文章中,我们将探讨如何部署到您自己的服务器。

结论 (Conclusion)

Meteor provides so many great tools to easily and quickly prototype your applications. Real-time, JavaScript client and server-side, the packages system, build system, minimongo, and so much more.

Meteor提供了许多出色的工具,可轻松快速地对应用程序进行原型制作。 实时,JavaScript客户端和服务器端,软件包系统,构建系统,minimongo等。

Hopefully this has given you a good taste of how quickly you can build an application in Meteor.

希望这使您对在Meteor中构建应用程序的速度有了很好的了解。

翻译自: https://scotch.io/tutorials/learn-meteor-js-from-scratch-build-a-polling-app

构建meteor应用程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值