流星html
Meteor is a web application platform.
流星是一个Web应用程序平台。
Modern web applications can be extremely complicated to write. Especially for beginners.
现代Web应用程序的编写可能非常复杂 。 特别是对于初学者。
Meteor is a tool for both beginners and experts, it makes it easy to start, and provides a huge ecosystem of libraries you can leverage.
Meteor是面向初学者和专家的工具,它使启动变得容易 ,并提供了可利用的庞大库生态系统。
JavaScript (JavaScript)
Meteor has been one of the first popular approaches to just use JavaScript both on the client, and on the server, seamlessly.
流星已经成为最早在客户端和服务器上无缝使用JavaScript的流行方法之一。
Coupled with MongoDB, which is a Database which stores JSON objects, and uses Javascript as a query language, it makes JavaScript ubiquitous.
与MongoDB结合使用, MongoDB是一个存储JSON对象并使用Javascript作为查询语言的数据库,它使JavaScript无处不在。
Meteor also ships with Minimongo in the frontend, which is a frontend database compatible with the MongoDB APIs, entirely written in JavaScript.
Meteor的前端还附带了Minimongo , Minimongo是与MongoDB API兼容的前端数据库,完全用JavaScript编写。
即时的 (Real-time)
Meteor is known for its real-time features, but what exactly is real-time? Suppose you want to create a chat app. Meteor offers you features that are perfect for that.
流星以其实时功能而闻名,但是实时到底是什么呢? 假设您要创建一个聊天应用程序。 流星为您提供了完美的功能。
Want to create an internal communication app? Perfect too. A project management app? Basically, any app in which users could be notified or things should be updated based on other users actions, or third part things such as API change the information displayed, the user viewing the app can be notified of those changes immediately, in a rather easy way compared to other solutions.
是否要创建内部通讯应用程序? 太完美了。 项目管理应用程序? 基本上,任何可以通知用户或应根据其他用户操作来更新事物的应用程序,或者诸如API之类的第三方事物都可以更改显示的信息,可以很容易地立即将这些更改通知给查看该应用程序的用户与其他解决方案相比。
感觉很快 (Feels fast)
A thing named Latency Compensation offers you a trick that enables the interface to feel dead fast even if it still need to communicate with a remote server. And best of all, it’s free for you in terms of implementation, meaning it’s backed in Meteor and you don’t have to do anything to enable it.
名为“ 延迟补偿 ”的东西为您提供了一个窍门,即使接口仍然需要与远程服务器进行通信,它也可以使接口快速消失。 最重要的是,它在实现方面对您是免费的,这意味着它已在Meteor中提供支持,您无需做任何事情即可启用它。
开源的 (Open Source)
Of course Meteor is entirely Open Source.
当然,Meteor完全是开源的。
这很简单 (It’s simple)
Things seem very simple in Meteor, because they are simple.
在流星中,事情看起来非常简单,因为它们很简单。
Complicated things lead to weird bugs or hard problems later. Meteor offers us a clean, beautiful API and functionality to build upon.
复杂的事情以后会导致奇怪的错误或困难的问题。 流星为我们提供了干净,漂亮的API和功能。
出色的包装系统 (A great package system)
The cool thing about Meteor is that since it can power both the frontend and the backend, and it’s deeply integrated with the database, both frontend and backend code can be put in a single package, and work seamlessly for us on both sides. That’s why we can add full user management with a single line of code.
关于Meteor的最酷的事情是,由于它既可以为前端和后端提供动力,又可以与数据库深度集成, 因此前端和后端代码都可以放在一个包中 ,并且可以为我们双方无缝地工作。 这就是为什么我们可以用一行代码来添加完整的用户管理。
流星如何改善生活 (How Meteor can improve your life)
Meteor gives you a Full-Stack platform, by providing both the client-side framework, and the server-side framework. What’s more, Meteor even provides you the communication channel between those. It’s called DDP, and we’ll talk about it later.
通过提供客户端框架和服务器端框架, Meteor为您提供了全栈平台 。 更重要的是,Meteor甚至为您提供了两者之间的沟通渠道。 它称为DDP ,我们稍后再讨论。
You no longer need to glue together different framework, languages, tooling and codebases. This is huge for the independent developer, small startups or even bigger organizations that don’t want to lose time and resources making things harder than they should be.
您不再需要将不同的框架,语言,工具和代码库粘合在一起。 对于不希望浪费时间和资源使事情变得比他们本应困难的独立开发人员,小型创业公司甚至更大的组织而言,这是巨大的。
当流星可能不适合您 (When Meteor might not be the best fit for you)
Static content websites have other better platforms to build upon. If you need to just output some HTML without a lot of interactivity, use a static site generator.
静态内容网站还有其他更好的平台可以建立。 如果您只需要输出一些没有太多交互性HTML,请使用静态网站生成器。
Meteor as of writing does not support SQL Databases, which can be a good thing in many cases, but they can be needed in other cases. Of course you can write your own procedures that use SQL Data.
在撰写本文时,Meteor不支持SQL数据库 ,这在很多情况下是一件好事,但在其他情况下可能需要它们。 当然,您可以编写自己的使用SQL数据的过程。
流星七原则 (The 7 Meteor Principles)
Meteor is built upon the following seven principles. They’re listed in the project documentation and they’re fundamental principles so we’ll report them here.
流星是基于以下七个原理构建的。 它们已列在项目文档中,它们是基本原理,因此我们将在此处报告。
Principles always matter when they’re respected in the everyday life.
原则在日常生活中受到尊重时总是很重要。
线上数据 (Data on the Wire)
Meteor doesn’t send HTML over the network. The server sends data and lets the client render it.
流星不会通过网络发送HTML。 服务器发送数据并让客户端呈现它。
一种语言 (One Language)
Meteor lets you write both the client and the server parts of your application in JavaScript.
Meteor允许您使用JavaScript编写应用程序的客户端和服务器部分。
数据库无处不在 (Database Everywhere)
You can use the same methods to access your database from the client or the server.
您可以使用相同的方法从客户端或服务器访问数据库。
延迟补偿 (Latency Compensation)
On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly.
在客户端上,Meteor会预取数据并模拟模型,以使其看起来像服务器方法调用立即返回。
全堆React性 (Full Stack Reactivity)
In Meteor, real-time is the default. All layers, from database to template, update themselves automatically when necessary.
在Meteor中,实时是默认设置。 从数据库到模板的所有层均在必要时自动更新。
拥抱生态 (Embrace the Ecosystem)
Meteor is open source and integrates with existing open source tools and frameworks.
Meteor是开源的,并且与现有的开源工具和框架集成在一起。
简单等于生产力 (Simplicity Equals Productivity)
The best way to make something seem simple is to have it actually be simple. Meteor’s main functionality has clean, classically beautiful APIs.
使某件事情看起来简单的最好方法是使它实际上简单。 流星的主要功能具有简洁经典的API。
安装步骤 (Installation procedure)
On OSX and Linux installing Meteor is as simple as typing this in the Operating System terminal:
在OSX和Linux上,安装Meteor就像在“操作系统”终端中键入以下命令一样简单:
curl https://install.meteor.com/ | sh
![Install Meteor](https://flaviocopes.com/meteor/meteor-install.png)
That’s it!
而已!
Windows has its own official installer, so check it out on the official site.
Windows有其自己的官方安装程序,因此请在官方网站上进行检查。
流星的第一步 (First steps with Meteor)
Let’s create the first Meteor app.
让我们创建第一个Meteor应用程序。
Open the Operating System terminal, go into the directory where you’ll host the project and type
打开操作系统终端,进入托管项目的目录,然后键入
meteor create hello-world
![Create a Meteor app](https://i-blog.csdnimg.cn/blog_migrate/af769ed8c251069cd8a5fb99e63ef1e1.png)
Meteor will create the new app for you, in the hello-world
directory.
流星将在hello-world
目录中为您创建新应用。
Now go inside that directory and type
现在进入该目录并输入
meteor
This will spin up the Meteor web server, and you’ll be able to reach your first Meteor app by pointing your browser at http://localhost:3000
这将启动Meteor Web服务器,您可以通过将浏览器指向http://localhost:3000
来访问第一个Meteor应用程序
![Hello Meteor](https://i-blog.csdnimg.cn/blog_migrate/ab5be456c9c973a072a682d33c226db0.png)
It was easy, right?
很简单,对吧?
代码演练 (Code walk-through)
Let’s walk through the app code to see how that works.
让我们遍历应用程序代码以了解其工作原理。
Do not worry if things are not much clear right now, many concepts will be introduced and explained later on.
如果现在事情还不太清楚,请不要担心,稍后将介绍和解释许多概念。
A few years ago this Meteor sample app would have contained just one JavaScript file, for both the client and server, using Meteor.isClient
and Meteor.isServer
to check if the app was running on the client, or on the server.
几年前,使用Meteor.isClient
和Meteor.isServer
检查该应用程序是在客户端还是在服务器上运行,此Meteor示例应用程序本应只包含一个用于客户端和服务器JavaScript文件。
The sample app moved away from this approach, and how has a server/main.js
file, and other files in client/
.
该示例应用程序摆脱了这种方法, server/main.js
使用server/main.js
文件以及client/
其他文件。
client / main.html (client/main.html)
If you open the client/main.html
file you can see the source code of the app:
如果打开client/main.html
文件,则可以看到该应用程序的源代码:
<head>
<title>hello-world</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
{{> info}}
</body>
<template name="hello">
<button>Click Me</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
<template name="info">
<h2>Learn Meteor!</h2>
<ul>
...
</ul>
</template>
Meteor recognizes the head
and body
tags and puts them in the correct place in the page content. This means that by including a head
tag, all its content will be added to the “real” page head
tag.
流星识别head
和body
标签,并将其放置在页面内容中的正确位置。 这意味着,通过包含head
标签,其所有内容都将添加到“真实”页面head
标签中。
Same thing applies to the body
tag. They are the two main tags.
同样的内容也适用于body
标签。 它们是两个主要标签。
All the rest of the application must be put in separate template
tags.
应用程序的所有其余部分必须放在单独的template
标记中。
The special {{ }}
parentheses you see are defined by Spacebars, which is a templating language very similar to Handlebars with some unique features that make it perfect to work with Meteor
您看到的特殊{{ }}
括号由Spacebars定义, Spacebars是一种模板语言,与Handlebars非常相似,具有一些独特的功能,非常适合与Meteor一起使用
In the hello-world example,
在hello-world示例中,
{{> hello}}
includes the hello
template, and
包括hello
模板,以及
{{counter}}
inside the hello
template looks for the counter value in the template context.
hello
模板中的内容将在模板上下文中查找计数器值。
客户端/ main.js (client/main.js)
This is the content of the client/main.js
file:
这是client/main.js
文件的内容:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
Template.hello.onCreated(function helloOnCreated() {
// counter starts at 0
this.counter = new ReactiveVar(0);
});
Template.hello.helpers({
counter() {
return Template.instance().counter.get();
},
});
Template.hello.events({
'click button'(event, instance) {
// increment the counter when button is clicked
instance.counter.set(instance.counter.get() + 1);
},
});
The code sets up a ReactiveVar, a reactive variable. A reactive variable exposes a setter and a getter. By using the setter, all functions that are retrieving the value using get() will be alerted when its value changes.
该代码设置了ReactiveVar,一个React变量 。 React变量公开了一个setter和一个getter。 通过使用setter,当值更改时,将使用get()检索所有使用该值的函数。
The value of the reactive variable is displayed in the HTML using the {{counter}}
snippet, which calls the counter()
template helper we defined here.
使用{{counter}}
代码段在HTML中显示React变量的值,该代码段调用了我们在此处定义的counter()
模板帮助程序。
It first initializes that variable to zero, and it sets its value to be incremented when the button is clicked in the hello
template.
它首先将该变量初始化为零,并在hello
模板中单击按钮时将其值设置为递增。
To handle clicks, you act on the events of the hello
template. In this case, we intercept the click on a button
HTML element. When this happens, you increment the Session.counter value.
要处理点击,您需要对hello
模板的事件进行操作。 在这种情况下,我们拦截button
HTML元素上的单击。 发生这种情况时,您增加Session.counter值。
In the Meteor server code, in server/main.js
, there’s a Meteor.startup
call, which just calls the passed function when Meteor is ready. Now there’s nothing in it, but we’ll see how this can be useful later.
在Meteor服务器代码的server/main.js
,有一个Meteor.startup
调用,它在Meteor准备就绪时才调用传递的函数。 现在没有任何内容,但是稍后我们将看到它如何有用。
流星CLI (The Meteor CLI)
When installing Meteor, you get the CLI (command line utility) called meteor
.
安装Meteor时,您会获得称为meteor
的CLI(命令行实用程序)。
It’s a super useful tool, you already used it to create the first app, and to start with we just need to know a small fraction of what it can do.
这是一个非常有用的工具,您已经使用它来创建第一个应用程序,并且从一开始我们只需要知道它可以做的一小部分。
Let’s introduce the four most useful commands you’ll use when starting with Meteor.
让我们介绍一下从Meteor开始使用的四个最有用的命令。
流星 (meteor)
If inside an empty directory you type
如果在空目录中,请键入
meteor
you’ll get an error because Meteor was not initialized in that directory.
您会收到错误消息,因为Meteor没有在该目录中初始化。
If you instead type meteor
in a folder that has a Meteor project already created (see meteor create
here below), Meteor will start up and create the server, initialize the database and you’ll be able to open the Meteor website.
如果您在已经创建了Meteor项目的文件夹中键入meteor
(请参见下面的meteor create
),Meteor将启动并创建服务器,初始化数据库,您将可以打开Meteor网站。
流星创造 (meteor create)
If inside a directory you type
如果在目录中键入
meteor create my_app_name
Meteor will initialize a new Meteor project in a subfolder named my_app_name
.
Meteor将在名为my_app_name
的子文件夹中初始化一个新的Meteor项目。
流星添加 (meteor add)
Inside your Meteor project already initialized, calling
在您的Meteor项目内部已经初始化,调用
meteor add package_name
will lookup the package_name
package and will install it in the current project.
将查找package_name
软件包并将其安装在当前项目中。
You can run this command in a separate terminal window while the Meteor app is running, and you’ll get the package functionality without the need to restart the Meteor server.
您可以在Meteor应用程序运行时在单独的终端窗口中运行此命令,并且无需重启Meteor服务器即可获得程序包功能。
流星删除 (meteor remove)
Inside your Meteor project already initialized, calling
在您的Meteor项目内部已经初始化,调用
meteor remove package_name
will remove the package with that name from your project.
将从您的项目中删除具有该名称的软件包。
同构 (Isomorphic)
The term isomorphic identifies a framework where client-side code and server-side code are written in the same language. This implies that any piece of code could run both on the server and on the client, unless it’s tied to a context-specific action.
术语“ 同构”表示一种框架,在该框架中,客户端代码和服务器端代码以相同的语言编写。 这意味着任何代码段都可以在服务器和客户端上运行 ,除非它与特定于上下文的操作相关联。
In the past 10 years Web Applications have been built by clearly separating the server and the client code. Server code run PHP, Ruby, Python code. That code could never work on the frontend-side, because the browser does not support those languages.
在过去的10年中,Web应用程序是通过将服务器代码和客户端代码明确分离而构建的。 服务器代码运行PHP,Ruby,Python代码。 该代码永远无法在前端运行,因为浏览器不支持这些语言。
Browsers are only capable of executing code written in JavaScript.
浏览器只能执行用JavaScript编写的代码。
With the meteoric rise of Node.js in the last few years, and what was built on top, now we have the chance to build an entire application in the same language: JavaScript.
在过去几年中,随着Node.js的飞速发展以及建立在顶部的东西,现在我们有机会使用相同的语言(JavaScript)来构建整个应用程序。
Meteor takes the isomorphic concept even further, by transparently running every file in your project, unless you don’t want it to do it, on both sides of the platform, doing different things based on the context, clearly explained by the Meteor documentation.
通过透明地运行项目中的每个文件(除非您不希望这样做),Meteor进一步扩展了同构概念,除非您不希望它在平台的两侧,都根据上下文做不同的事情 ,Meteor文档中对此进行了明确说明。
This is an amazing opportunity and advantage that Meteor enables by building a “super-platform” on top of Node.js and the Browser platforms, enabling you to build applications faster and better than ever.
通过在Node.js和浏览器平台之上构建“超级平台”,Meteor可以实现这令人惊奇的机遇和优势,从而使您能够比以往更快,更好地构建应用程序 。
Isomorphic refers to JavaScript code that runs with little to no modifications on the client and on the server. It’s code that takes care of both what runs inside the browser, and the what runs on the server.
同构是指在客户端和服务器上运行时几乎没有修改JavaScript代码。 该代码既照顾浏览器内部运行的内容,又照顾服务器上运行的内容。
Meteor is an isomorphic framework. This is great because we can write concise applications that now even share some pieces of code between client and server code.
流星是一个同构框架。 这很棒,因为我们可以编写简洁的应用程序,现在甚至可以在客户端和服务器代码之间共享一些代码。
It enables you to become a full-stack developer, because you no longer need to deeply know two separate stacks to work on both sides of the application.
它使您成为一名全栈开发人员,因为您不再需要深刻地了解两个独立的栈就可以在应用程序的两面工作。
The classical example is the one of an HTTP request. On the browser you’d do an AJAX call. On the server you’d use your stack-specific code.
经典示例是HTTP请求之一。 在浏览器上,您将进行AJAX调用。 在服务器上,您将使用特定于堆栈的代码。
Using Meteor, you can use the same function HTTP.get()
provided by the http
package, on both sides, just like when you install the Axios library.
使用Meteor,您可以在两侧使用由http
包提供的相同功能HTTP.get()
,就像安装Axios库时一样 。
Meteor.isServer,Meteor.isClient (Meteor.isServer, Meteor.isClient)
Meteor exposes two boolean variables to determine where the code is running:
流星公开了两个布尔变量来确定代码在哪里运行:
Meteor.isServer
Meteor.isServer
Meteor.isClient
Meteor.isClient
Put them inside an if
statement to run some code part just on one side of the platform.
将它们放在if
语句中,以仅在平台的一侧运行某些代码部分。
For example:
例如:
if (Meteor.isClient) {
alert('Hello dear user!')
} else if (Meteor.isServer) {
//running server-side
}
特殊目录 (Special directories)
Putting lots of Meteor.isServer
and Meteor.isClient
checks in the application is not ideal of course.
当然,在应用程序中放置许多Meteor.isServer
和Meteor.isClient
检查并不理想。
First, the code can quickly grow complicated and not nice to read. Second, even the server code is sent to the client. This is bad because you’d better keep server-side code private, and also because you send unnecessary code which slows down loading times.
首先,代码会Swift变得复杂,并且不好看。 其次,甚至服务器代码也被发送到客户端。 这很不好,因为您最好使服务器端代码保持私有状态,并且还因为发送不必要的代码会减慢加载时间。
That’s why Meteor has two special folders that automatically take care of the distinction for us: client
and server
这就是为什么Meteor具有两个特殊的文件夹,它们会自动为我们处理区别: client
和server
Whatever you put in the client
directory is not loaded on the server side.
无论您放置在client
目录中的什么内容都不会加载到服务器端。
Whatever you put in the server
directory is not sent to the client.
无论您放置在server
目录中的什么,都不会发送到客户端。
Another advantage of keeping this distinction is that assets put in the client folders are never taken into consideration during the build phases.
保持这种区别的另一个好处是,在构建阶段永远不会考虑放在客户端文件夹中的资产。
会话变量和模板助手 (Session variables and template helpers)
Here’s a simple example on combining Session variables and template helpers to achieve a simple case of selecting the current comment selected in a list.
这是一个简单的示例,该示例结合了Session变量和模板助手,以实现选择列表中所选当前注释的简单情况。
In our template.html
file:
在我们的template.html
文件中:
<template name="main">
{{#each comments}}
{{> comment}}
{{/each}}
</template>
<template name="comment">
<div class="{{#if selected}}selected{{/if}}">
<p>{{this.comment}}</p>
</div>
</template>
In template.js
:
在template.js
:
Session.set('selectedComment', null)
Template.main.helpers({
comments: function() {
return Comments.find()
}
})
Template.comment.helpers({
selected: function() {
return Session.equals('selectedComment', this._id)
}
})
Template.comment.events({
'click div' : function(e, t) {
Session.set('selectedComment', this._id)
}
})
In this case any time I click a comment, that comment becomes the selected comment, and we can show it full-size, fetch the other comments made by the user or do some other fancy stuff.
在这种情况下,每当我单击评论时,该评论即成为选定的评论,我们可以将其显示为完整尺寸,获取用户发表的其他评论或进行其他一些花哨的工作。
React式编程 (Reactive programming)
First, a clarification: Meteor’s reactivity has nothing to do with React, the other very popular JavaScript framework.
首先,澄清一下:流星的React性与另一个非常流行的JavaScript框架React无关。
What is reactive programming, you say? Reactive programming is a programming paradigm.
您说什么是React式编程? React式编程是一种编程范例。
Reactive programming is nothing new, nor something that Meteor introduced. But, what Meteor did was making reactive programming easy to use.
响应式编程并不是什么新鲜事物,也不是Meteor引入的东西。 但是,Meteor所做的是使React式编程易于使用。
Actually, you’re most probably already using reactive programming without even knowing about it.
实际上,您很可能已经在使用React式编程,甚至对此一无所知。
什么是React式编程 (What is reactive programming)
Reactive programming allows you to write code that automatically refreshes and re-calculates functions and values when something that you depend on changed.
响应式编程允许您编写代码,当您依赖的内容发生更改时,该代码会自动刷新并重新计算函数和值。
For example, data in the database changed? You need to re-display it in the client.
例如,数据库中的数据改变了吗? 您需要在客户端中重新显示它。
That variable that counts the number of comments changed because you added a comment? Everything that depends on it, or shows it, must react to that change and re-compute the values.
该变量计算的注释数是因为您添加了注释而更改了? 依赖或显示它的所有内容都必须对更改做出React并重新计算值。
That works by having Reactive Sources. The database for example is a reactive source. When something changes inside it, it notifies the JavaScript variables that depend on those changes. Those variables are invalidated and must be recalculated according to the new data available.
这可以通过使用React源来实现。 例如,数据库是React性来源。 当其中的某些内容发生更改时,它会通知依赖于这些更改JavaScript变量。 这些变量无效,必须根据可用的新数据重新计算。
React源 (Reactive sources)
Meteor has a list of things that are reactive, and those drive the entire application. Not everything is reactive, just those things listed here:
流星有一个React性的事物列表,这些事物驱动整个应用程序。 并不是所有的东西都是React性的,只是这里列出的那些东西:
Reactive variables, defined using
new ReactiveVar()
React变量,使用
new ReactiveVar()
定义The data coming from the database is a reactive data source, because by subscribing to a publication you get a cursor, and that cursor is reactive. Any change to the collection represented by the cursor will trigger a recomputation of anything that uses it.
来自数据库的数据是React性数据源,因为通过订阅发布您可以获得一个游标,并且该游标是React性的。 对光标所表示的集合的任何更改都会触发对使用它的任何内容的重新计算。
Talking about subscriptions, when a subscription is available on the client its
.ready()
method is called. That is a reactive data source.谈到订阅,当客户端上有订阅时,将调用其
.ready()
方法。 那是React性数据源。Session variables are a reactive data source. When one changes a session variable by using
.set()
, everything that depends on those will be recalculate or re-rendered.会话变量是React性数据源。 当使用
.set()
更改会话变量时,依赖于这些变量的所有内容都将重新计算或重新呈现。The user methods
Meteor.user()
andMeteor.userId()
are a reactive data source.用户方法
Meteor.user()
和Meteor.userId()
是React性数据源。Meteor.status()
, which is a client-side method that returns the current client-server connection status, is a reactive data source.Meteor.status()
是一种响应式数据源,它是一种客户端方法,可返回当前的客户端-服务器连接状态。Meteor.loggingIn()
, which returns true if the user is currently doing a login, is a reactive data source.Meteor.loggingIn()
是React性数据源,如果用户当前正在登录,则返回true。
React式计算 (Reactive computations)
Whatever changes upon a reactive source change is a reactive computation. It’s some piece of code, a function, that needs to run again when a reactive source it depends on changes.
React性源变化后的任何变化都是React性计算。 这是一段代码,一个函数,当它依赖于响应源时,需要再次运行。
An example of reactive computation is the template helpers: every time a reactive data source that involves a template helper changes, the template re-renders it.
模板助手是React式计算的一个示例:每次涉及模板助手的React性数据源发生更改时,模板都会重新渲染它。
定义自己的React式计算 (Defining your own reactive computations)
You can define your own reactive computations, and react when something changes upstream, by using Tracker.autorun()
.
您可以使用Tracker.autorun()
定义自己的React式计算,并在上游发生变化时做出React。
This function:
该功能:
Tracker.autorun(function () {
var currentPage = Session.get('currentPage')
alert("The current page is " + currentPage)
})
Will trigger an alert whenever you call Session.set('currentPage', 'whatever')
without you needing to add callbacks or other observers.
每当您调用Session.set('currentPage', 'whatever')
时都将触发警报Session.set('currentPage', 'whatever')
而无需添加回调或其他观察者。
流星出版物 (Meteor Publications)
One of the key features of Meteor is provided by the data layer.
数据层提供了Meteor的关键功能之一。
Since Meteor manages both the server and the client, I can explain the concept in this way:
由于Meteor同时管理服务器和客户端,因此我可以用这种方式解释这一概念:
- The server creates a publication 服务器创建发布
- The client subscribes to that publication 客户订阅该出版物
- Meteor keeps everything in sync 流星使一切保持同步
The server can precisely determine what each client will see. Each publication can be tailored upon parameters and user permissions.
服务器可以精确确定每个客户端将看到的内容。 每个发布都可以根据参数和用户权限进行定制。
Let’s do a simple Pub/Sub introduction on standard MongoDB collections.
让我们对标准MongoDB集合进行简单的发布/订阅介绍。
服务器发布 (Server publication)
Here’s an example of a server code creating a publication for comments that have been approved:
这是一个服务器代码示例,用于为已批准的注释创建发布:
//server-side code
Meteor.publish('comments', () => {
return Comments.find({ approved: true })
})
Or we want to create a publication for comments made on a specific article:
或者我们想创建一个出版物来发表对特定文章的评论:
Meteor.publish('comments', (articleId) => {
return Comments.find({ articleId: articleId })
})
The publish function is called every time a client subscribes.
每次客户端订阅时,都会调用publish函数。
客户订阅 (Client subscription)
On the client the code is very easy. For example, let’s subscribe to all comments:
在客户端上,代码非常简单。 例如,让我们订阅所有评论:
Meteor.subscribe('comments')
Let’s instead subscribe to comments made on the current article:
让我们订阅对当前文章发表的评论:
const articleId = 23
Meteor.subscribe('comments', articleId)
Once the subscribe method has been called, Meteor fills the client-side Minimongo (the MongoDB instance running on the client) with the data you chose to sent it.
一旦调用了subscription方法,Meteor就会使用您选择发送的数据填充客户端Minimongo(在客户端上运行的MongoDB实例)。
Typically the client-side database only gets some records, the minimum amount needed to initialize and work. You don’t replicate the whole server-side Mongo collection content of course, but you request data as needed.
通常,客户端数据库仅获取一些记录,这是初始化和工作所需的最低数量。 当然,您不会复制整个服务器端Mongo集合的内容,而是根据需要请求数据。
自动发布 (Autopublish)
Meteor makes it very easy for us to start diving into a project without worrying at all about publications and subscriptions.
流星使我们非常轻松地开始进入一个项目,而不必担心出版物和订阅。
It does this by including the autopublish
package in every new project. That that packages does is, it automatically creates a pub/sub for each collection we have defined, syncing all the data available from server to client.
它通过在每个新项目中包括autopublish
程序包来实现。 软件包所做的就是,它会为我们定义的每个集合自动创建一个发布/订阅,将服务器上所有可用数据同步到客户端。
When you’ll reach the phase when you need more control on the data available to each user or view, you’ll just remove the autopublish
package and you’ll manually define what you need.
当您需要进一步控制每个用户或视图可用数据的阶段时,您将删除autopublish
程序包,然后手动定义所需的内容。
Minimongo (Minimongo)
Minimongo is your best friend when developing in Meteor. Ok, if you feel you have lots of best friends when using Meteor, I feel the same. Everything in Meteor is provided to ease your life.
当在Meteor中开发时,Minimongo是您最好的朋友。 好的,如果您在使用Meteor时觉得自己有很多最好的朋友,我也有同感。 提供流星中的所有内容以缓解您的生活。
Minimongo, in particular, is a frontend implementation of MongoDB. You might say.. what? Why do I need another database?
特别是Minimongo,是MongoDB的前端实现。 你可能会说..什么? 为什么需要另一个数据库?
MongoDB:流星数据库 (MongoDB: The Meteor Database)
As of writing, Meteor has just one officially supported database: MongoDB.
在撰写本文时,Meteor只有一个官方支持的数据库:MongoDB。
You may wonder why. First, let me clarify: you can actually use any database you want, but to enjoy at 100% the marvels of Meteor you need to use Mongo. There are currently community projects that are working towards adding support for many other databases.
您可能想知道为什么。 首先,让我澄清一下:您实际上可以使用任何想要的数据库,但是要100%享受Meteor的奇迹,您需要使用Mongo。 当前,有一些社区项目正在努力增加对许多其他数据库的支持。
MongoDB用两个词 (MongoDB in two words)
MongoDB is a document-based database. It features high performance, high availability, easy scalability. It stores its documents in database collections. A document is a set of key-value pairs (JSON), and it has a dynamic schema. This means that each document does not need to have the same set of fields, but you have a great freedom in managing data.
MongoDB是基于文档的数据库。 它具有高性能,高可用性,易于扩展的特点。 它将其文档存储在数据库集合中。 文档是一组键值对(JSON),并且具有动态模式。 这意味着每个文档不需要具有相同的字段集,但是您在管理数据方面拥有极大的自由。
流星和MongoDB (Meteor and MongoDB)
As said, a MongoDB document is a JSON object. Meteor Collections are directly related to MongoDB collections, and the Meteor internals make sure that when data changes in a MongoDB Collection tracked by Meteor, the Meteor Collection is updated too.
如前所述,MongoDB文档是一个JSON对象。 Meteor集合与MongoDB集合直接相关,Meteor内部结构可确保当Meteor跟踪的MongoDB集合中的数据发生更改时,Meteor集合也进行更新。
Minimongo (Minimongo)
In short, in Meteor you typically create a collection, and that collection is available on both client and server code. When you do some database query or database processing, you don’t “think” whether you should do that operation on the client-side database, or the server-side database: to a certain extent, they’re mostly the same thing. And they talk to each other transparently.
简而言之,在Meteor中,您通常创建一个集合,该集合在客户端和服务器代码上都可用。 当您执行某些数据库查询或数据库处理时,您不会“思考”是否应该在客户端数据库或服务器端数据库上执行该操作:在某种程度上,它们基本上是同一回事。 他们透明地互相交谈 。
This means that when the server-side database (MongoDB) is updated by someone else or something happens in the app you’re using, or even you add something in a second browser window.. everything that’s stored in the database that interests your current session is pushed by the server MongoDB to the Minimongo running inside your browser.
这意味着当服务器端数据库(MongoDB)被其他人更新或您正在使用的应用程序中发生某些事情,或者甚至在第二个浏览器窗口中添加了某些内容时。服务器MongoDB将会话推入浏览器中运行的Minimongo。
The same happens for the opposite: you push a post to the Posts collection? Minimongo is updated immediately, while Meteor pushes the update to the MongoDB database server side.
反之亦然:您将帖子推送到Posts集合中? Minimongo立即更新,而Meteor将更新推送到MongoDB数据库服务器端。
This has the nice effect of making your changes, your pages and interactions feel immediate to the user.
这具有使用户立即进行更改,页面和交互的良好效果。
Minimongo是MongoDB客户端克隆 (Minimongo is a MongoDB client-side clone)
Minimongo tries to perfectly emulate a subset of MongoDB. You can insert data, remove data, search, sort, update.. with the same exact MongoDB APIs.
Minimongo尝试完美模拟MongoDB的子集。 您可以使用完全相同的MongoDB API插入数据,删除数据,搜索,排序,更新..。
This means you can also easily port some parts of your code from the server to the client-side very easily when it makes sense.
这意味着您可以在需要的时候轻松地将代码的某些部分轻松地从服务器移植到客户端。
客户端存储设施 (Client-side storage facility)
With Minimongo you have a fantastic client-side storage that you can query using the MongoDB Query functionalities.
使用Minimongo,您可以拥有出色的客户端存储,可以使用MongoDB Query功能进行查询。
You can of course create instances of a Minimongo collection just client-side, when you don’t have the need to sync a collection to the server.
当然,当您不需要将集合同步到服务器时,您当然可以只在客户端创建Minimongo集合的实例。
Not only, you can observe for database changes, and your interface can react to those changes easily.
您不仅可以观察数据库的变化,而且您的界面可以轻松应对这些变化。
延迟补偿 (Latency Compensation)
Latency Compensation is part of the Meteor Principles. There, it’s described in this way: on the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly.
延迟补偿是流星原则的一部分。 在那里,它是这样描述的: 在客户端上,Meteor预取数据并模拟模型,使其看起来像服务器方法调用立即返回 。
这是什么意思? (What does it mean?)
On a typical Web Application, when you do some kind of action, the action is passed to the server to be processed, and then you need to wait until the server responds, and then changes are applied to the page you’re interacting with.
在典型的Web应用程序上,当您执行某种操作时,该操作将传递给服务器进行处理,然后您需要等待服务器响应,然后将更改应用于与之交互的页面。
More modern applications rely on AJAX to provide a better turnaround and avoid refreshing a page on every action, but still many apps rely on the server response prior to taking any action. Better apps introduce some sort of latency compensation, but it’s a manual process.
较现代的应用程序依靠AJAX提供更好的周转时间,并避免在每个操作上刷新页面,但是仍然有许多应用程序在执行任何操作之前都依赖服务器响应。 更好的应用程序会引入某种延迟补偿,但这是一个手动过程。
Meteor introduces the concept of Latency Compensation deep into his philosophy and it’s enabled by default, without you needing to do anything special to work with it.
Meteor将“延迟补偿”的概念深深地引入了他的哲学中,并且默认情况下已启用它,而您无需为此做任何特殊的事情。
For example when you add an item to a collection, meanwhile the item will be sent to the server, it’s already added to the collection view on your page.
例如,当您将一个项目添加到集合中时,与此同时该项目将被发送到服务器,它已经被添加到页面上的集合视图中。
It feels better, because the app feels immediately responsive (it is).
感觉更好,因为该应用程序立即感觉到响应 。
If there is an error you’ll be notified later and you have the opportunity to handle things in the best way for each situation.
如果发生错误,您将在以后收到通知,您将有机会针对每种情况以最佳方式处理问题。
流星集合 (Meteor Collections)
An application typically needs to display data of some sort.
应用程序通常需要显示某种数据。
Be it messages, comments, posts, books, addresses, pictures.. everything is a collection of something.
无论是消息,评论,帖子,书籍,地址,图片..一切都是事物的集合。
Meteor being deeply integrated with MongoDB takes the Mongo database collection concept and takes it to the application level.
与MongoDB深度集成的Meteor采用了Mongo数据库收集概念,并将其带到了应用程序级别。
In both the client and server contexts, you’ll typically interact with data by interacting with data collections.
在客户端和服务器上下文中,通常都将通过与数据集合进行交互来与数据进行交互。
How does it work?
它是如何工作的?
创建您的第一个收藏 (Create your first collection)
Messages = new Mongo.Collection('messages')
This defines a global variable
messages, which will be visible across the entire App on client and server.
这定义了一个global variable
消息,这些消息将在客户端和服务器上的整个App中可见。
This code needs to run on both the client and the server, so you’ll put it for example under collections/messages.js
.
该代码需要同时在客户端和服务器上运行,因此您可以将其放在例如collections/messages.js
。
While the code running in the two environments is the same, what it does is different:
虽然在两种环境中运行的代码相同, 但是执行的操作却不同:
on the server it creates a Mongo collection if it’s not already existing, and then it will load the cursor in the
Messages
variable在服务器上,它会创建一个Mongo集合(如果尚不存在),然后将光标加载到
Messages
变量中on the client it will instantiate a Minimongo local collection. The app once instantiated will link that to the server-side collection, and will automatically keep them in sync.
在客户端上 ,它将实例化Minimongo本地集合。 实例化后,该应用程序会将其链接到服务器端集合,并将自动使其保持同步。
将项目添加到集合 (Adding items to a collection)
You’ll be able to insert items into a collection using the .insert()
method on the collection cursor:
您可以使用集合光标上的.insert()
方法将项目插入到集合中:
Messages.insert({message: "Hi"})
在模板中显示集合 (Showing the collection in the template)
In a template you can use the {{#each}}
Spacebars helper to navigate the collection and print all values stored in it:
在模板中,您可以使用{{#each}}
空格键助手来导航集合并打印存储在其中的所有值:
<template name="messages">
{{#each messages}}
{{message}}
{{/each}}
</template>
流星html