meteor 入门教程

04-01 23395人

meteor是一个开源的JavaScript的Web应用程序框架。meteor最早在2011年12月推出,其核心是分布式数据协议,它的出现是最大的黑客新闻的历史。

一、meteor设计理念

Meteor基础构架是 Node.JS + MongoDB,它把这个基础构架同时延伸到了浏览器端,如果 App用纯 JavaScript 写成,JS APIs 和 DB APIs 就可以同时在服务器端和客户端无差异地调用,本地和远程数据通过 DDP(Distributed Data Protocol)协议传输。因此部分应用如 TODO 列表,网络在线和离线下使用功能完全没有差异,动作响应和数据延迟也完全感觉不出来。

 二、meteor特点

1、非常愉快的用户体验

现代用户界面
 
一个应用程序,感觉就像Facebook或Twitter上的网络博客,或者像一个伟大的桌面应用程序 不是像一堆链路连接的网页

2、支持移动互联网
无论是pc浏览器还是手机或平板电脑的应用程序都丰富的支持。

 3、数据实时更新

服务器端和客户端之间数据实时更新,实现无缝衔接,服务器端内容更新,自动同步到客户端,用户不用刷新浏览器。

 4、超快的速度没有延迟

用户在客户端操作根本感觉不到延迟,让用户体验飞一般的速度。

5、开发简单

过去需要1000行代码的程序,使用meteor只需要10行搞定,过去需要一周完成的项目,现在只需要几个小时就可以完成。

 三、meteor开发教程

1、安装meteor

在OSX或Linux一个命令安装Meteor 的最新版本,打开终端,输入:curl https://install.meteor.com/ | sh,官方安装程序支持在x86和x86_64架构的Mac OS X 10.6(雪豹)及以上,和Linux。windows下载相应的Windows的版本。

 2、创建你的第一个应用程序

要创建一个Meteor应用程序,打开终端,输入:

meteor create simple-todos

创建Meteor程序项目的文件夹。

simple-todos.js       # 加载客户端和服务器上的js文件
simple-todos.html     # 定义模板的文件
simple-todos.css      # 定义样式的文件
.meteor               # 内部传输文件

运行新创建的应用程序:

cd simple-todos
meteor

http://localhost:3000 查看运行效果。用任何编辑工具todos.html里面的内容查看,在浏览器页面会自动与新的内容更新。我们称之为“热代码推送”。

 3、定义使用模板

创建列表代码:

<!-- simple-todos.html -->
<head>
  <title>Todo List</title>
</head>

<body>
  <div class="container">
    <header>
      <h1>Todo List</h1>
    </header>

    <ul>
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </ul>
  </div>
</body>

<template name="task">
  <li>{{text}}</li>
</template>
// simple-todos.js
if (Meteor.isClient) {
  // This code only runs on the client
  Template.body.helpers({
    tasks: [
      { text: "This is task 1" },
      { text: "This is task 2" },
      { text: "This is task 3" }
    ]
  });
}

浏览器运行结果

Todo List

This is task 1

分析这些代码的功能

html在Meteor模板的定义,并确定了三个顶级标签:<head>, <body>, and <template>,<template>编译成模板,其中可以包含HTML里面用{{> TEMPLATENAME}}或者在你的JavaScript与Template.templateName的引用。

添加数据到模板

所有的html代码被Meteor编译器编辑,Spacebars编译器使用双花括号包围语句,如{{#每个}}和{{#如果}}。

添加CSS

复制所有的CSS代码

/* CSS declarations go here */
body {
  font-family: sans-serif;
  background-color: #315481;
  background-image: linear-gradient(to bottom, #315481, #918e82 100%);
  background-attachment: fixed;

  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;

  padding: 0;
  margin: 0;

  font-size: 14px;
}


.container {
  max-width: 600px;
  margin: 0 auto;
  min-height: 100%;
  background: white;
}


header {
  background: #d2edf4;
  background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
  padding: 20px 15px 15px 15px;
  position: relative;
}


#login-buttons {
  display: block;
}


h1 {
  font-size: 1.5em;
  margin: 0;
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 1em;
}


form {
  margin-top: 10px;
  margin-bottom: -10px;
  position: relative;
}


.new-task input {
  box-sizing: border-box;
  padding: 10px 0;
  background: transparent;
  border: none;
  width: 100%;
  padding-right: 80px;
  font-size: 1em;
}


.new-task input:focus{
  outline: 0;
}


ul {
  margin: 0;
  padding: 0;
  background: white;
}


.delete {
  float: right;
  font-weight: bold;
  background: none;
  font-size: 1em;
  border: none;
  position: relative;
}


li {
  position: relative;
  list-style: none;
  padding: 15px;
  border-bottom: #eee solid 1px;
}


li .text {
  margin-left: 10px;
}


li.checked {
  color: #888;
}


li.checked .text {
  text-decoration: line-through;
}


li.private {
  background: #eee;
  border-color: #ddd;
}


header .hide-completed {
  float: right;
}


.toggle-private {
  margin-left: 5px;
}


@media (max-width: 600px) {
  li {
    padding: 12px 15px;
  }


  .search {
    width: 150px;
    clear: both;
  }


  .new-task input {
    padding-bottom: 5px;
  }

}
 

 3、集合工作存储

集合是存储Meteor永久性数据的方法,集合的特点是可以自动和服务器端和客户端进行访问,无需编写大量的服务器代码,集合支持的模板将自动显示最新数据。

创建一个集合的方法:MyCollection = new Mongo.Collection("my-collection"); Mongo创建的集合叫客户端集合,存放在客户端。

// simple-todos.js
Tasks = new Mongo.Collection("tasks");

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

 从控制台插入任务

通过服务器数据库添加文件到集合。

meteor mongo

 以上代码打开控制面板开发本地数据库。

db.tasks.insert({ text: "Hello world!", createdAt: new Date() });

 打开你的浏览器,你会发现你的浏览器自动更新了。

 4、添加一个任务

添加如下代码

<header>
  <h1>Todo List</h1>

  <!-- add a form below the h1 -->
  <form class="new-task">
    <input type="text" name="text" placeholder="Type to add new tasks" />
  </form>
</header>

下面是我们需要添加表单的提交事件JavaScript代码:

// Inside the if (Meteor.isClient) block, right after Template.body.helpers:
Template.body.events({
  "submit .new-task": function (event) {
    // This function is called when the new task form is submitted

    var text = event.target.text.value;

    Tasks.insert({
      text: text,
      createdAt: new Date() // current time
    });

    // Clear form
    event.target.text.value = "";

    // Prevent default form submit
    return false;
  }
});

现在,你的应用程序有一个新的输入字段要添加一个任务只需要输入到输入字段并按下回车键如果你打开一个新的浏览器窗口,然后再次打开该应用程序你会看到列表自动所有客户机之间的同步。

添加事件到模板

事件监听器被添加到模板中,通过调用Template.templateName.events(...),对键值进行监听。在我们的例子,我们监听CSS选择器,当你按下submit事件,事件处理函数被调用。

插入一个集合的方法:Tasks.insert().

集合排序方法:createdAt 。

Template.body.helpers({
  tasks: function () {
    // Show newest tasks first
    return Tasks.find({}, {sort: {createdAt: -1}});
  }
});

 

5、检查关闭和删除任务

让我们添加两个元素到任务模板,一个复选框和删除按钮:

<!-- replace the existing task template with this code -->
<template name="task">
  <li class="{{#if checked}}checked{{/if}}">
    <button class="delete">&times;</button>

    <input type="checkbox" checked="{{checked}}" class="toggle-checked" />

    <span class="text">{{text}}</span>
  </li>
</template>

我们已经添加了UI元素,但他们没有做任何事情。我们应该增加一些事件处理程序:

// In the client code, below everything else
Template.task.events({
  "click .toggle-checked": function () {
    // Set the checked property to the opposite of its current value
    Tasks.update(this._id, {$set: {checked: ! this.checked}});
  },
  "click .delete": function () {
    Tasks.remove(this._id);
  }
});

使用对象属性添加和删除

<li class="{{#if checked}}checked{{/if}}">

如果类存在那么添加到任务列表。

 6、部署应用程序

meteor deploy my_app_name.meteor.com

 上传程序输入http://my_app_name.meteor.com打开应用程序。

7、在AndroidiOS应用

在Android模拟器

meteor install-sdk android

这将帮助你安装所有必要的工具,从项目建立一个Android应用程序。当您完成安装的一切,键入:

meteor add-platform android

 

同意许可条款,请键入:

meteor run android

 

运行在Android设备上

meteor run android-device

部署服务器,运行:

meteor run android-device --mobile-server my_app_name.meteor.com

 

运行在iOS模拟器(仅限Mac)

meteor install-sdk ios

 

建设iOS应用程序

meteor add-platform ios
meteor run ios

 8、临时UI状态

我们需要一个复选框添加到我们的HTML:

<!-- add the checkbox to <body> right below the h1 -->
<label class="hide-completed">
  <input type="checkbox" checked="{{hideCompleted}}" />
  Hide Completed Tasks
</label>

 我们需要一个事件处理程序时,该复选框被选中或取消选中更新会话变量。

// Add to Template.body.events
"change .hide-completed input": function (event) {
  Session.set("hideCompleted", event.target.checked);
}

 

更新Session变量的状态

// Replace the existing Template.body.helpers
Template.body.helpers({
  tasks: function () {
    if (Session.get("hideCompleted")) {
      // If hide completed is checked, filter tasks
      return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
    } else {
      // Otherwise, return all of the tasks
      return Tasks.find({}, {sort: {createdAt: -1}});
    }
  },
  hideCompleted: function () {
    return Session.get("hideCompleted");
  }
});

 

9、添加用户帐户

meteor add accounts-ui accounts-password

 

{{> loginButtons}}

 

// At the bottom of the client code
Accounts.ui.config({
  passwordSignupFields: "USERNAME_ONLY" //配置用户名
});

 

新任务的事件处理程序:

Tasks.insert({
  text: text,
  createdAt: new Date(),            // current time
  owner: Meteor.userId(),           // _id of logged in user
  username: Meteor.user().username  // username of logged in user
});
{{#if currentUser}}
  <form class="new-task">
    <input type="text" name="text" placeholder="Type to add new tasks" />
  </form>
{{/if}}
<span class="text"><strong>{{username}}</strong> - {{text}}</span>

 

10、安全的方法

删除不安全代码:

meteor remove insecure

定义方法:

// At the bottom of simple-todos.js, outside of the client-only block
Meteor.methods({
  addTask: function (text) {
    // Make sure the user is logged in before inserting a task
    if (! Meteor.userId()) {
      throw new Meteor.Error("not-authorized");
    }

    Tasks.insert({
      text: text,
      createdAt: new Date(),
      owner: Meteor.userId(),
      username: Meteor.user().username
    });
  },
  deleteTask: function (taskId) {
    Tasks.remove(taskId);
  },
  setChecked: function (taskId, setChecked) {
    Tasks.update(taskId, { $set: { checked: setChecked} });
  }
});

更新使用方法:

// replace Tasks.insert( ... ) with:
Meteor.call("addTask", text);

// replace Tasks.update( ... ) with:
Meteor.call("setChecked", this._id, ! this.checked);

// replace Tasks.remove( ... ) with:
Meteor.call("deleteTask", this._id);

11、发布和订阅过滤数据

用程序开始与自动发布包:

meteor remove autopublish

指定哪些服务信息发送给客户端

// At the bottom of simple-todos.js
if (Meteor.isServer) {
  Meteor.publish("tasks", function () {
    return Tasks.find();
  });
}
// At the top of our client code
Meteor.subscribe("tasks");


实施私有任务

<!-- add right below the code for the checkbox in the task template -->
{{#if isOwner}}
  <button class="toggle-private">
    {{#if private}}
      Private
    {{else}}
      Public
    {{/if}}
  </button>
{{/if}}

<!-- modify the li tag to have the private class if the item is private -->
<li class="{{#if checked}}checked{{/if}} {{#if private}}private{{/if}}">

我们需要修改我们的JavaScript代码在三个地方:

// Define a helper to check if the current user is the task owner
Template.task.helpers({
  isOwner: function () {
    return this.owner === Meteor.userId();
  }
});

// Add an event for the new button to Template.task.events
"click .toggle-private": function () {
  Meteor.call("setPrivate", this._id, ! this.private);
}

// Add a method to Meteor.methods called setPrivate
setPrivate: function (taskId, setToPrivate) {
  var task = Tasks.findOne(taskId);

  // Make sure only the task owner can make a task private
  if (task.owner !== Meteor.userId()) {
    throw new Meteor.Error("not-authorized");
  }

  Tasks.update(taskId, { $set: { private: setToPrivate } });
}
 欢迎访问我的博客 www.sitcoder.com
  • I leave a leave a response each time I appreciate a post on a website or if
    I have something to contribute to the discussion. Usually it is a result of the
    fire displayed in the article I browsed. And on this article meteor  入门教程.
    I was moved enough to write a thought :-) I do have some questions for you if it's allright.
    Is it simply me or do a few of the remarks appear
    like coming from brain dead visitors? :-P And, if you are writing at additional online social
    sites, I'd like to keep up with everything new you have to post.
    Would you make a list all of all your shared sites like your Facebook page,
    twitter feed, or linkedin profile?

  • Larry Fitzgerald has seen a allotment of the world.
    Conditions he's dollop others be aware it, too, according to a production http://www.arizonacardinalsteamonline.com/larry-fitzgerald-jersey in Condé Nast.
    The Arizona Cardinals wide receiver has his own company, Nomad Hill, "a Globe-trotting trips Originate callers dedicated to creating life-changing experiences quest of our guests."
    Condé Nast Traveler profiled Fitzgerald and the company in a story published Monday.
    Anna Katherine Clemmons offers an backing bowels look at Fitzgerald and the entourage in the story.
    She writes:
    "When his off-season begins, the 33-year-old Minnesota intrinsic chooses new places to by while also scheduling returns to favorite spots, like Tanzania. But whether it’s his in front or fifth anon a punctually visiting, Fitzgerald doesn’t hardly loaf on a bank or abide in a b & b with a stay service menu.
    '“I’m a yesterday's news guy, and I love positively getting to remember the people in the countries that I’m visiting,” Fitzgerald said in the story. “I like to push myself fa嘺de of my soothe zone.”'
    Fitzgerald's admiration instead of go has been properly documented thoroughly the years.
    In 2015, he sat down with us to talk on every side visiting the Kremlin, surfing volcanoes in Nicaragua and his terminal http://www.arizonacardinalsteamonline.com/larry-fitzgerald-jersey vacation.
    "I haven't gone to hiatus besides," Fitzgerald said. "That's absolutely on my scuttle list."
    Among Fitzgerald's travels:
    He explored Asia pro 45 days through himself after his first NFL season.
    He took trips with his people on all sides the Collective States growing up, visiting Mount Rushmore, Yellowstone Patriotic Woodland and Glacier Nationalistic Reserve, centre of other sites.
    He's visited Cambodia and biked across Vietnam.
    He's been to the Siwa Fertile patch in Egypt.
    He's ventured to Ethiopia, where he helped farmers with irrigation during a drought.
    He's met and talked with a CIA operative in Russia, and had samurai sword lessons in Japan.
    The company:
    In July 2016, Fitzgerald launched Nomad Hill with David Jones, a [url=http://www.arizonacardinalsteamonline.com/larry-fitzgerald-jersey][b]larry fitzgerald jersey[/b][/url] constant traveler whom Fitzgerald met approximately seven years ago.
    The companionship offers millennials more immersive vacations.
    “The travel industry, mainly in the high destination, has radical the millennial to themselves because they don’t know how to arrangement with them,” Jones said in the Condé Nast Traveler story. “It’s a distinctive population. It’s not very recently about going on a spell; it’s about experiences. They want to be spoken for in their experiences because they’ve been engaged in what they’ve done their total life.”
    “I like to be given up discernible and venture about, and David is the in any event approach,” Fitzgerald told Condé Nast Traveler. “I appear like I am a nomad.”  http://www.footballofficialsauthentic.com/  http://www.artsneed.com http://www.basketballofficialauthentic.com/

  • http://www.nfljerseys.us/ NFL Jerseys
    值得学习

    http://www.yeezyboost350.us.com/ Yeezy Boost 350 V2

    http://www.longchampbags.us.com/ Longchamp Handbags

    http://www.adidas-uk.org.uk/ Adidas UK

    http://www.yeezys.org/ Yeezys

    http://www.nike-stores.fr/ Nike Store

    http://www.underarmouroutlet.us.com/ Under Armour Outlet

    http://www.timberlanduk.org.uk/ Timberland Boots

    http://www.jordan12.us/ Jordan 12

    http://www.yeezy-shoes.us.com/ Yeezy Shoes

    http://www.nikehuarache.us/ nike huarache

    http://www.kedsshoesforwomen.com/ Keds Shoes For Women

    http://www.yeezy.com.co/ Yeezy Shoes

    http://www.nikeairmax.us/ Nike Air Max 2017

    http://www.outlettoms.us/ Toms Outlet

    http://www.ultraboostuncaged.us/ Ultra Boost

    http://www.mlb-jerseys.us/ MLB Jerseys

    http://www.adidas-nmds.com/ Adidas NMD

    http://www.oakleyoutlet.net.co/ Oakley Outlet

    http://www.rboutlet.org/ Ray Ban Outlet

    http://www.katespadeoutlets.us/ Kate Spade Outlet

    http://www.adidas-outlet.org/ Adidas Outlet

    http://www.nikeairmax-90.com/ Nike Air Max 90

    http://www.timberland-outlet.us/ Timberland Outlet

    http://www.rayban-sunglasses.ca/ Ray-Ban Sunglasses

    http://www.adidas-nmd.org.uk/ Adidas UK

    http://www.adidaseqt.com/  Adidas EQT

    http://www.ralphlaurens.org.uk/ Ralph Lauren UK

    http://www.jordan4.us/ Jordan 4

    http://www.cheapjordan-shoes.com/ Cheap Jordan

    http://www.adidasnmdoutlet.com/ NMD Outlet

  • Eliminating Silos: The Importance of an Enterprise Output Strategy inside Manufacturing Industry <a href="http://printing-in-china.com/label-printing/">sticker printing</a> <a href="http://printing-in-china.com/office-supplies/">business supplies</a> <a href="http://printing-in-china.com/book-printing/">publish books</a> By WhatTheyThink Staff Published: October 19, 2005 ,Capturing the Clicks: Eight tricks for making internet marketing that basically works  
    Digital Printing at drupa 鈥?Part 1 ,<a href="http://printing-in-china.com/label-printing/">label printer</a> <a href="http://printing-in-china.net/">printing services</a> <a href="http://printing-in-china.com/box-printing/">package printing</a>  I failed to list printing presses or bindery systems (if it absolutely was 1460 I would list the press). Graph Expo can be your only chance to view a huge selection presses and finishing systems in a place previously and I expect that a significant few will likely be sold. I am seeing two and even three older presses being replaced by one new high-productivity press. Based of what are going to be introduced in relation to spot color technology, you will need a press with an increase of units. ,<a href="http://printing-in-china.com/box-printing/">color printing service</a> <a href="http://printing-in-china.com/box-printing/">color print</a> <a href="http://printing-in-china.com">business card printing</a>  
    printing-in-china.com Paul Vogel was brought beyond retirement through the USPS for taking over as President of USPS&rsquo; newly created Digital Solutions group three weeks ago. He was managing director of the Global business from 2006-2009. His USPS career has exceeded 40 years. On the Policy Direction Panel Mr. Vogel offered, &ldquo;All ideas discussed (as of this Postal Vision Conference) have already been analyzed with the USPS ad nausea. For example, the durability vehicles (comprising the USPS 200,000 fleet) were anticipated to last 18 years and are also now 25 yrs old. The USPS will not want to spend to switch these vehicles&rdquo; (for alternative Federal Agencies&rsquo; shared use) because the USPS isn't going to discover how for a longer time they may last. &ldquo;Focus groups have already been in2 session for that last five months that can help USPS decide what digital services to supply.&rdquo; While kick starting this new enterprise, he may also be searching for a successor to his position. ,<a href="http://printing-in-china.com/box-printing/">product boxes</a> <a href="http://printing-in-china.net/">printing in china</a> <a href="http://printing-in-china.com/office-supplies/">office supply storage</a>  Define the Problem First .
    http://tempatnakal.com/member.php?116396-Rogerobemy http://maxwellinterior.com/gallery/#comment-5641 http://cs-intel.prv.pl/profile.php?mode=viewprofile&u=808 http://esvk.email/news4sport/showthread.php?tid=62478 http://www.kannfe.org/kannfe/index.php?option=com_kunena&func=view&catid=2&id=51516&Itemid=66#51516 http://straseni.unimedia.info/news/trenul-chisinau-ocnita-defectat-in-straseni--3149.html http://thetaxforum.co.uk/member.php?action=profile&uid=1186599 http://dhakagsm.net/index.php?action=profile;u=2916 http://www.stpaulsunited.ca/?contact-form-id=1213&contact-form-sent=2064&_wpnonce=2e5df025f6 http://forum.wercan.com/viewtopic.php?f=94&t=5683

  • [url=http://www.beatsbydre-wireless.org]beats by dre headphones[/url]
    [url=http://www.nikeairmaxcz.cz]nike air max p谩nsk茅[/url]
    [url=http://www.scarpeshogan2016.it]scarpe hogan[/url]
    [url=http://www.louboutinshoesoutlets.us]christian louboutin[/url]
    [url=http://www.north-faceoutletstore.us.com]the north face jackets[/url]
    [url=http://www.adidasboty2016.cz]adidas ultra boost[/url]
    [url=http://www.airmax-2017.org]nike air max 2016[/url]
    [url=http://www.airjordan-11.fr]air jordans[/url]
    [url=http://www.airmax-90.cz]nike air max 90[/url]
    [url=http://www.airmaxboty.cz]nike air max p谩nsk茅[/url]
    [url=http://www.airjordan11.us.com]jordan 11[/url]
    [url=http://www.katespade-handbags.us]kate spade bags[/url]
    [url=http://www.fitflop-clearance.com]fitflop shoes[/url]
    [url=http://www.longchamps-sacs.fr]longchamp[/url]
    [url=http://www.air-max-90.it]nike air max[/url]
    [url=http://www.air--max.org]cheap nike air max[/url]
    [url=http://www.jordan7210.us.com]jordan 11 72-10[/url]
    [url=http://www.airmax2017.net]nike air max 2017[/url]
    [url=http://www.nikeairmaxs2016.cz]nike air max p谩nsk茅[/url]
    [url=http://www.adidasnmd-forsale.us.com]adidas ultra boost[/url]

  • mst

    值得学习'

  • mst

    很好,值得学习

  • 
    
    	
    色迷迷 哭 呕吐 大笑 口水 微笑 啵一个 发怒

    Hi,您需要填写昵称和邮箱!

    • 必填项
    • 必填项