Day 15:Meteor —— 从零开始创建一个 Web 应用
到目前為止我們討論了Bower、AngularJS、GruntJS和PhoneGap等JavaScript技術。今天是“30天學習30種新技術”挑戰的第15天,我決定重返JavaScript,學習Meteor框架。雖然Meteor的文檔相當好,但是它缺少為初學者準備的教程。我覺得教程的學習效果更好,因為教程可以幫助你快速上手一種技術。本文將介紹如何利用 Meteor 框架構建一個epoll應用。
Meteor是什么?
Meteor是新一代的開發即時web應用的開源框架,它能幫助你在最少的時間內完成開發。它的理念和AngularJS、BackboneJS等框架大不相同。當我們在backbone 和 angular 上工作時,客戶端(Angular或Backbone)和REST后端通訊。我們可以用任何技術寫 REST 后端,例如 Java、NodeJS、PHP。
Meteor使用DDP(分布式數據協議)在客戶端和服務器間傳送數據。客戶端JavaScript開發者需要解決的首要問題是:向后端的數據庫發起查詢,發送數據到客戶端,當數據庫變動時,推送變動到客戶端。DDP是解決這一問題的標準做法。
Meteor應用的后端基于Node和MongoDB。前端和后端的應用同時使用Meteor的API。未來開發者可以選擇 MongoDB 之外的其他數據庫。
為什么使用Meteor?
請閱讀Meteor的七大原則。
應用案例
本文中我們將搭建一個 epoll 應用,該應用允許用戶發布問題并投票。這個應用可以做到:
-
當用戶訪問/時,會看到一個問題列表。用戶需要通過Twitter登錄,以便投票或發布新問題。如下圖所示,由于未登錄,投票按鈕不可用。
-
當用戶點擊Sign in with Twitter之后,他將授權 epoll 應用使用他的賬號。授權成功之后,用戶可以投票或發布新問題。
GitHub倉庫
今天的示例應用的代碼可以從GitHub取得。
安裝Meteor
開始使用Meteor很容易。如果你使用Mac或Linux,只需輸入如下命令:
curl https://install.meteor.com | /bin/shWindows用戶請參閱文檔
創建Meteor應用
創建Meteor應用很容易。安裝之后,運行create命令即可。
meteor create epoll這將創建epoll目錄,該目錄下有一些模板文件。項目結構如下所示:
讓我們解釋下這個結構:
meteor文件夾下保存meteor特定的文件。.gitignore忽略存儲MongoDB數據庫文件和應用文件的local文件夾。packages指明本應用所需的包。你可以把它們看成是npm包。Meteor以包的形式提供功能。本文中會使用一些包。release保存了meteor版本。本文使用的版本是0.6.6.3。
epoll.css決定應用的CSS樣式。
epoll.html是應用的HTML標記。目前meteor只支持handlebars模板引擎,不過未來可能支持其他模板引擎。
epoll.js是meteor應用的核心。epoll.js同時部署在服務器段和客戶端。這允許開發者一次編寫、兩端使用。meteor創建的epoll.js模板如下所示:
Meteor.isServer和Meteor.isClient區分了服務器端和客戶端的代碼。
meteor命令可以運行應用:
cd epoll meteor可以通過 http://localhost:3000 訪問應用。點擊按鈕后,在chrome developer tools中你可以看到You pressed the button.信息。
修改epoll.js的歡迎部分:
Template.hello.greeting = function () {return "The Missing Meteor Tutorial!!!";};變動會自動應用,頁面也會自動刷新。
MongoDB在哪?
前面提到Meteor使用MongoDB來存儲數據。當我們安裝meteor的時候,它同時會下載最新版的MongoDB。我們可以看到,MongoDB安裝在<user.home>/.meteor目錄。使用ps -ef可以找到MongoDB的安裝位置。
; ps -ef|grep mongo501 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在我的機子上,MongoDB運行于3002端口,以避免和其他默認運行于27017端口的MongoDB沖突。
智能的Meteor包管理
前面提到Meteor以包的形式實現功能。這些包在瀏覽器和服務器上都能使用。運行以下命令可以得知Meteor支持的所有包:
meteor list使用meteor add和meteor remove命令來添加刪除包。
添加Twitter Bootstrap包
我們將使用Twitter Bootstrap作為用戶界面的風格。
meteor add bootstrap注意,Meteor包不一定是最新版。
添加Twitter授權包
在我們的應用中,用戶需要首先通過Twitter授權才能投票或添加問題。Meteor提供了accounts-ui包,可以為我們的應用添加登錄組件:
meteor add accounts-ui然后我們添加授權提供者。在這個應用中,我們使用Twitter,不過我們其實也可以使用facebook、github、google、weibo或meetup。
meteor add accounts-twitter添加包之后,我們需要更新下epoll.html,添加Twitter登錄按鈕:
<head><title>Epoll : Share your opinion online, anywhere, anytime</title></head><body><div class="navbar navbar-static-top navbar-inverse"><div class="navbar-inner"><div class="container"><a class="brand" href="/">Epoll</a><ul class="nav pull-right"><li>{{loginButtons}}</li></ul></div></div></div><div class="container" id="main">{{> banner}}</div> </body><template name="banner"><div class="container"><div class="row"><div class="span6"><div class="well"><h4>Sign in using Twitter to submit new questions or to vote on existing questions.</h4>{{loginButtons}}</div></div></div></div> </template>然后調整一下樣式,增加下面的代碼到epoll.css:
/* CSS declarations go here */ .login-display-name{color: white } .login-button{background-color: white}#main {padding-top:20px; }應用會自動更新,你會見到這樣的頁面:
現在點擊Configure Twitter Login,會要求我們輸入 twitter 應用的相關信息:
按照提示配置之后,我們可以使用twitter登錄了。
授權之后我們可以登錄應用。使用完畢之后,我們可以登出。
MongoDB會在用戶集合內創建新用戶。我們可以使用mongo命令連接數據庫查看:
; ~/.meteor/tools/0b2f28e18b/mongodb/bin/mongo --port 3002MongoDB 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","accessTokenSecret" : "xxx","profile_image_url" : "http://pbs.twimg.com/profile_images/378800000254412405/e4adcf8fb7800c3e5f8141c561cb57e4_normal.jpeg","profile_image_url_https" : "https://pbs.twimg.com/profile_images/378800000254412405/e4adcf8fb7800c3e5f8141c561cb57e4_normal.jpeg","lang" : "en"},"resume" : {"loginTokens" : [{"token" : "xxx","when" : ISODate("2013-11-11T18:03:23.489Z")}]}},"profile" : {"name" : "Shekhar Gulati"} } >定義應用層次
Meteor創建的模板應用有一個問題,客戶端和服務器段的epoll.js代碼是一樣的。任何人的都可以使用瀏覽器的開發工具查看epoll.js。
如果我們不想將服務器端的特有代碼發送到客戶端,我們可以使用client和server目錄來分隔代碼。
cd epoll mkdir client server在兩個目錄下分別創建epollclient.js和epollserver.js文件。
client/epollclient.js內存放客戶端代碼:
Template.hello.greeting = function () {return "The Missing Meteor Tutorial!!!"; };Template.hello.events({'click input' : function () {// template data, if any, is available in 'this'if (typeof console !== 'undefined')console.log("You pressed the button");} });服務器端代碼存放在server/epollserver.js:
Meteor.startup(function () {// code to run on server at startup});```然后刪除`epoll.js`:```sh rm -f epoll.js移除insecure包
每一個Meteor應用預裝了insecure包。這個應用讓用戶端可以在數據庫上實施一切操作。對于原型開發這很有用,但是通常不適合生產環境。
meteor remove insecure發布問題
現在我們添加一個功能,已登錄的用戶可以提交新問題。
<head><title>Epoll : Share your opinion online, anywhere, anytime</title> </head><body><div class="navbar navbar-static-top navbar-inverse"><div class="navbar-inner"><div class="container"><a class="brand" href="/">Epoll</a><ul class="nav pull-right"><li>{{loginButtons}}</li></ul></div></div></div><div class="container" id="main">{{#if currentUser}}{{> addquestion}}{{/if}}{{#unless currentUser}}{{> banner}}{{/unless}}</div> </body><template name="banner"><div class="container"><div class="row"><div class="span6"><div class="well"><h4>Sign in using Twitter to submit new questions or to vote on existing questions.</h4>{{loginButtons}}</div></div></div></div> </template> <template name="addquestion"><textarea rows="3" class="input-xxlarge" name="questionText" id="questionText" placeholder="Add Your Question"></textarea><br/><input type="button" class="btn-info add-question" value="Add Question"/> </template>僅當用戶登錄的時候才會渲染addQuestion模板。如果用戶登出,則不會見到添加新問題的文本框。
我們需要同時更新客戶端和服務器端的代碼以便實現這一功能。
在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 = "";} });以上代碼中:
我們首先將點擊input事件綁定到add-question類。
接著我們阻止默認的點擊事件,從DOM中獲取問題文本。
然后我們調用Meteor服務器的方法addQuestion。由服務器負責插入、更新、刪除數據等有風險的操作。客戶端看不到實現,也無法私自修改數據。
現在我們需要修改server/epollserver.js。我們首先定義一個名為Questions的新集合。然后我們會操作這個集合。Meteor使用minimongo作為API接口。參閱Meteor.Collection.documentation查看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;} });現在訪問我們的應用然后提交一個新問題:
查看下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" }問題列表
我們接下來要實現的功能是問題列表。用戶不需登錄,就可以看到所有問題的列表。
在main div中加入:
{{> questions}}然后添加問題模板:
<template name="questions"><h2>All Questions</h2>{{#each items}}{{> question}}{{/each}} </template><template name="question"><div><p class="lead">{{questionText}}<a class="btn btn-small btn-success yes {{#unless currentUser}}disabled{{/unless}}" href="#"><i class="icon-thumbs-up"></i> Yes {{yes}}</a><a class="btn btn-small btn-danger no {{#unless currentUser}}disabled{{/unless}}" href="#"><i class="icon-thumbs-down"></i> No {{no}}</a></p></div> </template>注意我們使用了unless來確保用戶未登錄的情況下應用disabled css。
為了獲取所有問題,我們需要在客戶端使用Question集合來獲取所有文本。在client/epollclient.js添加如下代碼:
Questions = new Meteor.Collection("questions");Template.questions.items = function(){return Questions.find({},{sort:{'submittedOn':-1}}); };實現投票功能
最后我們需要實現投票功能。我們上面已經在html文件中加入了相關的模板代碼,下面我們在client/epollclient.js加入如下代碼:
Template.question.events({'click': function () {Session.set("selected_question", this._id);},'click a.yes' : function (event) {event.preventDefault();if(Meteor.userId()){var questionId = Session.get('selected_question');console.log('updating yes count for questionId '+questionId);Meteor.call("incrementYesVotes",questionId);}},'click a.no': function(){event.preventDefault();if(Meteor.userId()){var questionId = Session.get('selected_question');console.log('updating no count for questionId '+questionId);Meteor.call("incrementNoVotes",questionId);}}});上面的代碼實現了:
綁定點擊事件到問題模板。點擊任意問題的時,在session中設置questionId。session提供了一個客戶端的全局對象,你可以在里面存儲任意的鍵值對。
當用戶點擊Yes按鈕時,我們會從session中取得選中的questionId,然后在服務器端調用incrementYesVotes方法。我們使用Meteor.userId()來確保用戶已經登錄了。
當用戶點擊No按鈕時,我們在服務器端調用incrementNoVotes函數。
最后我們在server/epollserver.js加入incrementYesVotes和incrementNoVotes函數。我們使用Meteor的集合更新功能來增加計數器。
incrementYesVotes : function(questionId){console.log(questionId);Questions.update(questionId,{$inc : {'yes':1}});},incrementNoVotes : function(questionId){console.log(questionId);Questions.update(questionId,{$inc : {'no':1}}); }這樣每次用戶點擊yes或no按鈕之后,計數器會更新。你可以訪問 http://localhost:3000 試驗一番。
部署Meteor應用
部署Meteor應用有很多種方法。我們可以在Meteor提供的測試服務器上部署,也可以部署到OpenShift。
如果你打算部署到OpenShift上,請參閱Ryan的這篇博客。
運行以下命令可以部署到Meteor測試服務器:
meteor deploy epoll應用可以通過 http://epoll.meteor.com/ 訪問。
今天就是這些了。歡迎繼續反饋。
原文:Day 15: Meteor——Building a Web App From Scratch in Meteor
翻譯整理: Segmentfault
總結
以上是生活随笔為你收集整理的Day 15:Meteor —— 从零开始创建一个 Web 应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Day14:使用斯坦福 NER 软件包实
- 下一篇: Day 16: Goose Extrac