Meteor - 基于Node.js和MongoDB的全栈开发框架

来源:互联网 发布:怎样更换淘宝密码 编辑:程序博客网 时间:2024/06/07 05:48

Meteor安装与运行

Meteor 是基于Node.js、MongoDB的全栈框架,使用之后发现Meteor很另类,它把更多的工作放到了前端,确切地说应该是混淆了前后端

安装(Mac or Linux)

执行下面的语句

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

查看帮助

meteor --help

创建项目

meteor create learnmeteor

learnmeteor目录会生成如下文件

learnmeteor.js # a JavaScript file loaded on both client and serverlearnmeteor.html # an HTML file that defines view templateslearnmeteor.css # a CSS file to define your app's styles.meteor # internal Meteor files

运行

cd learnmeteormeteor

在浏览器打开http://localhost:3000

热代码推送

当保存修改的文件时,浏览器自动更新新内容,这个技术叫热代码推送(hot code push)


模板Spacebars

Meteor的默认模板叫Spacebars, 是Handlebars的变形

Tips

在模板中不能写DOCTYPE声明

Can't set DOCTYPE here.  (Meteor sets <!DOCTYPE html> for you)

也不能写html元素

bad formatting in HTML template

所以Meteor的模板根元素只能有<head> <body> <template>

<head>  <meta charset="UTF-8">  <title>Document</title></head><body>  <h1>Welcome</h1>  {{> hello}}</body><template name="hello">  <button>Click Me</button>  <p>You've pressed the button {{counter}} times.</p></template>

在HTML中定义Templates

<head>  <meta charset="UTF-8">  <title>My website!</title></head><body>  <h1>Hello!</h1>  {{> welcomePage}}</body><template name="welcomePage">  <p>Welcome to my website</p></template>

helpers

helpers用来给模板传递数据

helpers可以是values

Template.nametag.helpers({  name: "Ben Bitdiddle"});

也可以是functions

Template.nametag.helpers({    gender: function () {        return 'Man'    }});

也可以给函数传参

Template.nametag.helpers({    age: function (num) {        return num    }});


//模板<head>  <meta charset="UTF-8">  <title>My website!</title></head><body>  <h1>Hello!</h1>  {{> welcomePage}}</body><template name="welcomePage">  <p>Welcome to my website, {{name}}, {{sex}}, {{age 26}}</p></template>//jsif (Meteor.isClient) {  Template.welcomePage.helpers({    name: 'boy',    sex: function () {      return 'Man'    },    age: function (num) {      return num    }  })}

Spacebars的控制结构

{{#each data}} … {{/each}}

//模板<head>  <meta charset="UTF-8">  <title>My website!</title></head><body>  <h1>Hello!</h1>  {{> welcomePage}}</body><template name="welcomePage">  {{#each people}}  <p>Welcome to my website, {{name}}</p>  {{/each}}</template>//jsif (Meteor.isClient) {  Template.welcomePage.helpers({    people: [{name: 'baby'}, {name: 'god'}, {name: 'boby'}]  })}

{{#if data}} … {{else}} … {{/if}}

这个很理解

{{#with data}} … {{/with}}

设置data上下文,功能和js中的with语句是一个意思

events

为模板指定事件处理程序

key的第一部分表示事件,第二部分表示almost any selector supported by JQuery

事件处理函数有两个参数,第一个参数是事件对象,第二个参数是模板实例

//模板<head>  <meta charset="UTF-8">  <title>My website!</title></head><body>  <h1>Hello!</h1>  {{> welcomePage}}</body><template name="welcomePage"> <button class="welcome">Welcome</button></template>//jsif (Meteor.isClient) {  Template.welcomePage.events({    'click .welcome': function (event, template) {      console.log(event)      console.log(template)    }  })}

onRendered

注册一个函数,当模板实例插入到DOM时触发

Template.codeSample.onRendered(function () {  hljs.highlightBlock(this.findAll('pre'));});

模板实例

template.findAll(selector)

从模板实例中选择符合CSS选择器的所有元素

template.find(selector)

从模板实例中选择符合CSS选择器的第一个元素


Session

当使用Session.set时,Session.get会自动变化

Session.set(key, value)

key - String value - EJSON-able Object or undefined 

Session.get(key)

//模板<head>  <meta charset="UTF-8">  <title>My website!</title></head><body>  <h1>Hello!</h1>  {{> welcomePage}}</body><template name="welcomePage"><button>change</button><p>{{counter}}</p></template>//jsif (Meteor.isClient) {  Session.set('default-counter', 1)  Template.welcomePage.helpers({    // 点击按钮时,数字不变    //counter: Session.get('default-counter')    // 点击按钮时,数字会变化    counter: function () {      return Session.get('default-counter')    }  })  Template.welcomePage.events({    'click button': function () {      Session.set('default-counter', Session.get('default-counter')+1)      console.log(Session.get('default-counter'))      //Session.set('default-counter', Session.get('default-counter')+1)    }  })}

Tracker

当Session variables, database queries, and other data sources变化时,执行Tracker中函数

Tracker.autorun(runFunc, [onError])

runFunc Function onError Function 


Tracker.autorun(function () {    //有了这一句才行    var c = Session.get('default-counter')    console.log('do something')})

Collections

Meteor在collections中存储数据,需要先使用new Mongo.Collection声明一个collection

Posts = new Mongo.Collection("posts")Comments = new Mongo.Collection("comments")

下面列出操作collection的函数

new Mongo.Collection(name, [options])collection.findOne([selector], [options])collection.find([selector], [options])collection.insert(doc, [callback])collection.update(selector, modifier, [options], [callback])collection.remove(selector, [callback])collection.allow(options)collection.deny(options)

Accounts

让用户使用Let users log in with passwords, Facebook, Google, GitHub, etc.

{{> loginButtons}}

Meteor.user

Meteor.userId

Meteor.users

{{currentUser}}


Methods

Methods are server functions that can be called from the client.

Meteor.methods(methods)

Meteor.call(name, [arg1, arg2…], [asyncCallback])

new Meteor.Error(error, [reason], [details])


发布和订阅

Meteor servers can publish sets of documents with Meteor.publish, and clients can subscribe to those publications with Meteor.subscribe. Any documents the client subscribes to will be available through the find method of client collections.

By default, every newly created Meteor app contains the autopublish package, which automatically publishes all available documents to every client.

禁止自动发布

meteor remove autopublish

Now you can use Meteor.publish and Meteor.subscribe to control what documents flow from the server to its clients.


Environment

Meteor.isClient

布尔值

Meteor.isServer

布尔值

Meteor.isServer can be used to limit where code runs, but it does not prevent code from being sent to the client. Any sensitive code that you don’t want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server directory.

Meteor.startup(func)

Run code when a client or a server starts.

if (Meteor.isClient) {}if (Meteor.isServer) {  Meteor.startup(function () {    // code to run on server at startup  });}

0 0
原创粉丝点击