Merge pull request #7017 from meteor/move-docs-to-own-repo

Removed docs, pointed people at new repo
This commit is contained in:
Tom Coleman
2016-05-11 09:43:13 -07:00
78 changed files with 4 additions and 18779 deletions

View File

@@ -85,6 +85,10 @@ Finally, you can show your support for features you would like by commenting wit
A great way to contribute to Meteor is by helping keep the issues in the repository clean and well organized. This process is called 'issue triage' and the steps are described [here](IssueTriage.md).
## Documentation
If you'd like to contribution to Meteor's documentation, head over to https://github.com/meteor/docs and create issues or pull requests there.
## Making changes to Meteor core
Eventually you may want to change something in a core Meteor package, or

View File

@@ -1,13 +0,0 @@
# This file contains information which helps Meteor properly upgrade your
# app when you run 'meteor update'. You should check it into version control
# with your project.
notices-for-0.9.0
notices-for-0.9.1
0.9.4-platform-file
notices-for-facebook-graph-api-2
1.2.0-standard-minifiers-package
1.2.0-meteor-platform-split
1.2.0-cordova-changes
1.2.0-breaking-changes
1.3.0-split-minifiers-package

View File

@@ -1 +0,0 @@
local

View File

@@ -1,7 +0,0 @@
# This file contains a token that is unique to your project.
# Check it into your repository along with the rest of this directory.
# It can be used for purposes such as:
# - ensuring you don't accidentally deploy one app on top of another
# - providing package authors with aggregated statistics
tqr1dmhdrd0990n71v

View File

@@ -1,28 +0,0 @@
# Meteor packages used by this project, one per line.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.
jquery
underscore
showdown
spiderable
appcache
reload-safetybelt
simple:markdown-templating
simple:highlight.js
less
meteor-base
mobile-experience
mongo
blaze-html-templates
session
tracker
logging
reload
random
ejson
spacebars
check
standard-minifier-css
standard-minifier-js

View File

@@ -1,3 +0,0 @@
server
browser
ios

View File

@@ -1 +0,0 @@
METEOR@1.3

View File

@@ -1,76 +0,0 @@
allow-deny@1.0.2
appcache@1.0.8
autoupdate@1.2.6
babel-compiler@6.5.2
babel-runtime@0.1.6
base64@1.0.6
binary-heap@1.0.6
blaze@2.1.5
blaze-html-templates@1.0.2
blaze-tools@1.0.6
boilerplate-generator@1.0.6
caching-compiler@1.0.2
caching-html-compiler@1.0.4
callback-hook@1.0.6
check@1.1.2
ddp@1.2.3
ddp-client@1.2.3
ddp-common@1.2.3
ddp-server@1.2.4
deps@1.0.10
diff-sequence@1.0.3
ecmascript@0.4.1
ecmascript-runtime@0.2.8
ejson@1.0.9
fastclick@1.0.9
geojson-utils@1.0.6
hot-code-push@1.0.2
html-tools@1.0.7
htmljs@1.0.7
http@1.1.3
id-map@1.0.5
jquery@1.11.6
launch-screen@1.0.8
less@2.5.6
livedata@1.0.16
logging@1.0.10
markdown@1.0.7
meteor@1.1.12
meteor-base@1.0.2
minifier-css@1.1.9
minifier-js@1.1.9
minimongo@1.0.12
mobile-experience@1.0.2
mobile-status-bar@1.0.10
modules@0.5.1
modules-runtime@0.6.1
mongo@1.1.5
mongo-id@1.0.2
npm-mongo@1.4.41
observe-sequence@1.0.9
ordered-dict@1.0.5
promise@0.6.5
random@1.0.7
reactive-dict@1.1.5
reactive-var@1.0.7
reload@1.1.6
reload-safetybelt@1.0.7
retry@1.0.5
routepolicy@1.0.8
session@1.1.3
showdown@1.0.6
simple:highlight.js@1.2.0
simple:markdown-templating@1.2.7
spacebars@1.0.9
spacebars-compiler@1.0.9
spiderable@1.0.11
standard-minifier-css@1.0.4
standard-minifier-js@1.0.4
templating@1.1.7
templating-tools@1.0.2
tracker@1.0.11
ui@1.0.9
underscore@1.0.6
url@1.0.7
webapp@1.2.6
webapp-hashing@1.0.7

View File

@@ -1,31 +0,0 @@
#!/usr/bin/env bash
echo "Please run this script from the docs app folder."
echo "Make sure you have phantomjs installed!"
DOCS_FOLDER=$(pwd);
METEOR_FOLDER=$(dirname ${DOCS_FOLDER});
# make temporary folder
mkdir /tmp/docsdiff
cd /tmp/docsdiff
# trigger phantomjs to give us actual HTML
curl "localhost:3000/?_escaped_fragment_=key1=value1" > new
curl "docs.meteor.com/?_escaped_fragment_=key1=value1" > old
# use our handy canonicalize script copy-pasted from the test-helpers package
# maybe there is a way to use the actual package?
${METEOR_FOLDER}/scripts/node.sh "${DOCS_FOLDER}/private/canonicalize.js" new > new1
${METEOR_FOLDER}/scripts/node.sh "${DOCS_FOLDER}/private/canonicalize.js" old > old1
# remove some of the things we want to ignore, you might want to change these
cat new1 | sed "s/new-api-box//g" | sed "s/ class=\"api-title\"//g" > new2
cat new2 | sed "s/<p><\/p>//g" > new3
cat new3 | sed "s/i>/em>/g" > new4
cat old1 | sed "s/new-api-box//g" | sed "s/ class=\"api-title\"//g" > old2
cat old2 | sed "s/<p><\/p>//g" > old3
cat old3 | sed "s/i>/em>/g" > old4
# git diff is more colorful than regular diff
/usr/bin/git diff -U10 --no-index --ignore-blank-lines -w old4 new4

View File

@@ -1,91 +0,0 @@
<template name="apiBoxTitle">
<h3 id="{{id}}" class="api-title">
<div class="locus">
{{locus}}
</div>
<a class="name selflink" href="{{link}}">{{{name}}}</a>
<div class="subtext">
{{#if importName}}
<code>import { {{importName}} } from 'meteor/{{module}}'</code>
{{/if}}
{{#if fullApi}}
{{#if filepath}}
<a class="src-code" href="https://github.com/meteor/meteor/blob/master/packages/{{filepath}}#L{{lineno}}" target="_blank">
({{filepath}}, line {{lineno}})
</a>
{{/if}}
{{/if}}
</div>
</h3>
</template>
<template name="autoApiBox">
{{#with apiData this}}
<div class="api {{bare}} new-api-box">
{{> apiBoxTitle
name=signature
importName=importName
module=module
locus=locus
id=id filepath=filepath
lineno=lineno
}}
<div class="desc">
{{#markdown}}{{summary}}{{/markdown}}
</div>
{{#if paramsNoOptions}}
<h4>Arguments</h4>
<dl class="args">
{{#each paramsNoOptions}}
<dt>
<span class="name">{{name}}</span>
<span class="type">{{{typeNames type.names}}}</span>
</dt>
<dd>
{{{description}}}
</dd>
{{/each}}
</dl>
{{/if}}
{{#if options}}
<h4>Options</h4>
<dl class="args">
{{#each options}}
<dt>
<span class="name">{{name}}</span>
<span class="type">{{{typeNames type.names}}}</span>
</dt>
<dd>
{{{description}}}
</dd>
{{/each}}
</dl>
{{/if}}
{{#if UI.contentBlock}}
{{#markdown}}{{> UI.contentBlock}}{{/markdown}}
{{/if}}
</div>
{{/with}}
</template>
<template name="api_box_args">
<dl class="args">
{{#each this}}
<dt><span class="name">{{{name}}}</span>
<span class="type">
{{#if type_link}}
<a href="#{{type_link}}">{{{type}}}</a>
{{else}}
{{{type}}}
{{/if}}
</span></dt>
<dd>{{#markdown}}{{{descr}}}{{/markdown}}</dd>
{{/each}}
</dl>
</template>

View File

@@ -1,202 +0,0 @@
var apiData = function (options) {
options = options || {};
if (typeof options === "string") {
options = {name: options};
}
var root = DocsData[options.name];
if (! root) {
console.log("API Data not found: " + options.name);
}
if (_.has(options, 'options')) {
root = _.clone(root);
var includedOptions = options.options.split(';');
root.options = _.filter(root.options, function (option) {
return _.contains(includedOptions, option.name);
});
}
return root;
};
var typeLink = function (displayName, url) {
return "<a href='" + url + "'>" + displayName + "</a>";
};
var toOrSentence = function (array) {
if (array.length === 1) {
return array[0];
} else if (array.length === 2) {
return array.join(" or ");
}
return _.initial(array).join(", ") + ", or " + _.last(array);
};
var typeNameTranslation = {
"function": "Function",
EJSON: typeLink("EJSON-able Object", "#ejson"),
EJSONable: typeLink("EJSON-able Object", "#ejson"),
"Tracker.Computation": typeLink("Tracker.Computation", "#tracker_computation"),
MongoSelector: [
typeLink("Mongo Selector", "#selectors"),
typeLink("Object ID", "#mongo_object_id"),
"String"
],
MongoModifier: typeLink("Mongo Modifier", "#modifiers"),
MongoSortSpecifier: typeLink("Mongo Sort Specifier", "#sortspecifiers"),
MongoFieldSpecifier: typeLink("Mongo Field Specifier", "#fieldspecifiers"),
JSONCompatible: "JSON-compatible Object",
EventMap: typeLink("Event Map", "#eventmaps"),
DOMNode: typeLink("DOM Node", "https://developer.mozilla.org/en-US/docs/Web/API/Node"),
"Blaze.View": typeLink("Blaze.View", "#blaze_view"),
Template: typeLink("Blaze.Template", "#blaze_template"),
DOMElement: typeLink("DOM Element", "https://developer.mozilla.org/en-US/docs/Web/API/element"),
MatchPattern: typeLink("Match Pattern", "#matchpatterns"),
"DDP.Connection": typeLink("DDP Connection", "#ddp_connect")
};
Template.autoApiBox.helpers({
apiData: apiData,
typeNames: function typeNames (nameList) {
// change names if necessary
nameList = _.map(nameList, function (name) {
// decode the "Array.<Type>" syntax
if (name.slice(0, 7) === "Array.<") {
// get the part inside angle brackets like in Array<String>
name = name.match(/<([^>]+)>/)[1];
if (name && typeNameTranslation.hasOwnProperty(name)) {
return "Array of " + typeNameTranslation[name] + "s";
}
if (name) {
return "Array of " + name + "s";
}
console.log("no array type defined");
return "Array";
}
if (typeNameTranslation.hasOwnProperty(name)) {
return typeNameTranslation[name];
}
if (DocsData[name]) {
return typeNames(DocsData[name].type);
}
return name;
});
nameList = _.flatten(nameList);
return toOrSentence(nameList);
},
signature: function () {
var signature;
var escapedLongname = _.escape(this.longname);
if (this.istemplate || this.ishelper) {
if (this.istemplate) {
signature = "{{> ";
} else {
signature = "{{ ";
}
signature += escapedLongname;
var params = this.params;
var paramNames = _.map(params, function (param) {
var name = param.name;
name = name + "=" + name;
if (param.optional) {
return "[" + name + "]";
}
return name;
});
signature += " " + paramNames.join(" ");
signature += " }}";
} else {
var beforeParens;
if (this.scope === "instance") {
beforeParens = "<em>" + apiData(this.memberof).instancename + "</em>." + this.name;
} else if (this.kind === "class") {
beforeParens = "new " + escapedLongname;
} else {
beforeParens = escapedLongname;
}
signature = beforeParens;
// if it is a function, and therefore has arguments
if (_.contains(["function", "class"], this.kind)) {
var params = this.params;
var paramNames = _.map(params, function (param) {
if (param.optional) {
return "[" + param.name + "]";
}
return param.name;
});
signature += "(" + paramNames.join(", ") + ")";
}
}
return signature;
},
importName: function () {
const noImportNeeded = !this.module
|| this.scope === 'instance'
|| this.ishelper
|| this.istemplate;
// override the above we've explicitly decided to (i.e. Template.foo.X)
if (!noImportNeeded || this.importfrompackage) {
if (this.memberof) {
return this.memberof.split('.')[0];
} else {
return this.name;
}
}
},
id: function () {
if (Session.get("fullApi") && nameToId[this.longname]) {
return nameToId[this.longname];
}
// fallback
return this.longname.replace(/[.#]/g, "-");
},
paramsNoOptions: function () {
return _.reject(this.params, function (param) {
return param.name === "options";
});
},
fullApi: function () {
return Session.get("fullApi");
}
});
Template.apiBoxTitle.helpers({
link: function () {
return '#/' + (Session.get("fullApi") ? 'full' : 'basic') + '/' + this.id;
}
});
Template.autoApiBox.onRendered(function () {
this.$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});

View File

@@ -1,69 +0,0 @@
<template name="basicIntroduction">
<div id="introduction">
<!-- clicking this anchor in the left bar should scroll to top of doc,
not here -->
{{#markdown}}
_**Meteor is an ultra-simple environment for building modern websites.
What once took weeks, even with the best tools, now takes hours with
Meteor.**_
The web was originally designed to work in the same way that mainframes
worked in the 70s. The application server rendered a screen and sent it
over the network to a dumb terminal. Whenever the user did anything,
that server rerendered a whole new screen. This model served the Web
well for over a decade. It gave rise to LAMP, Rails, Django, PHP.
But the best teams, with the biggest budgets and the longest schedules,
now build applications in JavaScript that run on the client. These apps
have stellar interfaces. They don't reload pages. They are reactive:
changes from any client immediately appear on everyone's screen.
They've built them the hard way. Meteor makes it an order of
magnitude simpler, and a lot more fun. You can build a complete
application in a weekend, or a sufficiently caffeinated hackathon. No
longer do you need to provision server resources, or deploy API
endpoints in the cloud, or manage a database, or wrangle an ORM layer,
or swap back and forth between JavaScript and Ruby, or broadcast data
invalidations to clients.
{{> quickStart}}
<h2 id="learning-resources">Learning Resources</h2>
<!-- https://github.com/blog/273-github-ribbons -->
<a href="http://github.com/meteor/meteor"><img class="github-ribbon visible-desktop" style="position: absolute; top: 0; right: 0; border: 0;" src="/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a>
There are many community resources for getting help with your app. If Meteor
catches your interest, we hope you'll get involved with the project!
<dl class="involved">
<dt><span>Tutorial</span></dt>
<dd>Get started fast with the <a href="https://www.meteor.com/install">official Meteor tutorial</a>!
</dd>
<dt><span>Stack Overflow</span></dt>
<dd>The best place to ask (and answer!) technical questions is on <a href="http://stackoverflow.com/questions/tagged/meteor">Stack
Overflow</a>. Be sure to add
the <code>meteor</code> tag to your question.
</dd>
<dt><span>Forums</span></dt>
<dd>Visit the <a href="https://forums.meteor.com">Meteor discussion
forums</a> to announce projects, get help, talk about the community,
or discuss changes to core.
</dd>
<dt><span>GitHub</span></dt>
<dd>The core code is on <a href="http://github.com/meteor/meteor">GitHub</a>. If you're able to write code or file issues, we'd love to have your help. Please read <a href="https://github.com/meteor/meteor/wiki/Contributing-to-Meteor">Contributing to Meteor</a> for how to get started.
</dd>
</dl>
{{/markdown}}
</div>
{{> commandLine}}
{{> basicFileStructure}}
{{> basicMobile}}
</template>

View File

@@ -1,155 +0,0 @@
var section = function (title, options) {
return _.extend({}, {
type: "section",
title: title,
}, options);
};
var item = function (name, options) {
if (! options) {
options = {
longname: name
};
}
return _.extend({}, {
type: "item",
name: name
}, options);
};
var sections = [
section("", {
subsections: [
section("Quick Start", {
id: "quickstart"
}),
section("Learning Resources", {
id: "learning-resources"
}),
section("Command Line Tool", {
id: "command-line"
}),
section("File Structure", {
id: "filestructure"
}),
section("Building Mobile Apps", {
id: "buildingmobileapps"
})
]
}),
section("Templates", {
id: "templates",
subtitle: "Create views that update automatically when data changes",
items: [
item("Defining templates in HTML", {id: "defining-templates"}),
item("Template.<em>name</em>.helpers", {longname: "Template#helpers"}),
item("Template.<em>name</em>.events", {longname: "Template#events"}),
item("Template.<em>name</em>.onRendered", {longname: "Template#onRendered"}),
item("<em>template</em>.findAll", {longname: "Blaze.TemplateInstance#findAll"}),
item("<em>template</em>.find", {longname: "Blaze.TemplateInstance#find"})
]
}),
section("Session", {
id: "session",
subtitle: "Store temporary data for the user interface",
items: [
item("Session.set"),
item("Session.get")
]
}),
section("Tracker", {
id: "tracker",
subtitle: "Re-run functions when data changes",
items: [
item("Tracker.autorun")
]
}),
section("Collections", {
id: "collections",
subtitle: "Store persistent data",
items: [
item("Mongo.Collection"),
item("<em>collection</em>.findOne", {longname: "Mongo.Collection#findOne"}),
item("<em>collection</em>.find", {longname: "Mongo.Collection#find"}),
item("<em>collection</em>.insert", {longname: "Mongo.Collection#insert"}),
item("<em>collection</em>.update", {longname: "Mongo.Collection#update"}),
item("<em>collection</em>.remove", {longname: "Mongo.Collection#remove"}),
item("<em>collection</em>.allow", {longname: "Mongo.Collection#allow"}),
item("<em>collection</em>.deny", {longname: "Mongo.Collection#deny"}),
]
}),
section("Accounts", {
id: "accounts",
subtitle: "Let users log in with passwords, Facebook, Google, GitHub, etc.",
items: [
item("{{> loginButtons}}", {id: "loginButtons"}),
item("Meteor.user"),
item("Meteor.userId"),
item("Meteor.users"),
item("{{currentUser}}", {longname: "currentUser"})
]
}),
section("Methods", {
id: "methods",
subtitle: "Call server functions from the client",
items: [
item("Meteor.methods"),
item("Meteor.call"),
item("Meteor.Error")
]
}),
section("Publish / Subscribe", {
id: "pubsub",
subtitle: "Sync part of your data to the client",
items: [
item("Meteor.publish"),
item("Meteor.subscribe")
]
}),
section("Environment", {
id: "environment",
subtitle: "Control when and where your code runs",
items: [
item("Meteor.isClient"),
item("Meteor.isServer"),
item("Meteor.startup")
]
}),
section("Packages", {
id: "packages",
subtitle: "Choose from thousands of community packages",
items: [
item("Searching for packages", {id: "searchingforpackages"}),
item("accounts-ui", {id: "accountsui"}),
item("coffeescript"),
item("email"),
item("jade"),
item("jquery"),
item("http"),
item("less"),
item("markdown"),
item("underscore"),
item("spiderable")
]
})
];
var linkPrefix = "#/basic/";
var linkFromIdLongname = function (id, longname) {
if (id) {
return linkPrefix + id;
} else if (longname) {
return linkPrefix + longname.replace(/[#.]/g, "-");
}
};
Template.basicTableOfContents.helpers({
sections: sections,
linkForItem: function () {
return linkFromIdLongname(this.id, this.longname);
},
maybeCurrent: function () {
return Session.get('urlHash') === linkFromIdLongname(this.id, this.longname)
? 'current' : '';
}
});

View File

@@ -1,32 +0,0 @@
{{#template name="quickStart"}}
## Quick start!
Meteor supports [OS X, Windows, and Linux](https://github.com/meteor/meteor/wiki/Supported-Platforms).
On Windows? [Download the official Meteor installer here](https://install.meteor.com/windows).
On OS X or Linux? Install the latest official Meteor release from your terminal:
```bash
$ curl https://install.meteor.com/ | sh
```
The Windows installer supports Windows 7, Windows 8.1, Windows Server
2008, and Windows Server 2012. The command line installer supports Mac OS X
10.7 (Lion) and above, and Linux on x86 and x86_64 architectures.
Once you've installed Meteor, create a project:
```bash
meteor create myapp
```
Run it locally:
```bash
cd myapp
meteor
# Meteor server running on: http://localhost:3000/
```
{{/template}}

File diff suppressed because it is too large Load Diff

View File

@@ -1,759 +0,0 @@
/** CSS reset **/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-family: inherit;
font-size: 100%;
vertical-align: baseline;
}
body {
line-height: 1;
color: black;
background: white;
}
ol, ul {
list-style: none;
}
a img {
border: none;
}
/** Basics **/
body {
font-family: 'Helvetica Neue', Helvetica, Arial;
}
pre {
font-family: monospace;
}
code {
font-family: monospace;
white-space: pre;
font-size: 1.2em;
}
pre code {
font-size: 1.1em;
}
ul {
list-style-type: disc;
margin-top: 1em;
margin-bottom: 1em;
padding-left: 40px;
}
dl {
margin-top: 1em;
margin-bottom: 1em;
}
dd {
margin-left: 40px;
}
h1, h2, h3, h4 {
color: black;
font-weight: bold;
}
h1 {
font-size: 2em;
}
h1 {
margin: 1.5em 0 .67em 0;
}
h2 {
font-size: 1.5em;
margin: 1.25em 0 .5em 0;
}
h3 {
font-size: 1.17em;
margin: 1em 0 1em 0;
}
h4 {
}
p {
margin-bottom: 1em;
}
em {
font-style: italic;
}
a:hover {
background-color: yellow;
}
/** Main pane **/
#main {
margin: 10px;
line-height: 1.3;
color: #333333;
}
#main strong {
font-weight: bold;
}
#main h1 {
border-style: solid none none none;
border-color: #999;
border-width: 2px;
}
#main h2 span {
background-color: yellow;
margin: 0px -5px 0px -5px;
padding: 2px 5px 2px 5px;
}
#main a:link, #main a:visited {
text-decoration: none;
border-bottom: 1px dashed #000;
color: inherit;
}
#main code a:link, #main code a:visited {
border: none;
}
dl.involved {
padding-left: 10px;
}
dl.involved dt {
text-transform: uppercase;
font-weight: bold;
}
dl.involved dt span {
background-color: yellow;
}
dl.involved dd {
margin-left: 20px;
margin-bottom: 1em;
}
dl.involved a {
font-weight: bold;
}
dl.involved code {
font-weight: bold;
}
dl.example dt {
font-weight: bold;
margin-left: 10px;
}
dl.example dd {
margin-bottom: 10px;
}
dl.objdesc dt {
margin-top: 1em;
margin-left: 1.5em;
}
dl.objdesc dt .name {
font-weight: bold;
}
dl.objdesc dt .type {
margin-left: 15px;
font-size: .9em;
font-weight: 200;
color: black;
}
dl.objdesc dd {
margin-bottom: 1em;
margin-left: 1.5em;
}
dl.callbacks dt .name, dl.methods dt .name {
/* like code tag */
font-family: monospace;
font-size: 1.1em;
}
dl.callbacks {
margin-left: 1.5em;
}
#main dd p {
margin-top: 0.5em;
}
/** API **/
.warning {
border-width: 0px 0px 0px 3px;
border-style: solid;
border-color: red;
margin: 21px 0px 21px 10px;
padding-left: 15px;
font-weight: bold;
color: red;
}
.note {
border-width: 0px 0px 0px 2px;
border-style: solid;
border-color: black;
margin: 21px 0px 21px 10px;
padding-left: 15px;
font-style: italic;
color: black;
}
.api {
border: 1px solid #ddd;
margin-bottom: 1em;
margin-top: 2em;
}
.bareapi {
border-width: 0;
}
.api h3, h3.api-title {
background: #eee;
padding: 5px 10px;
}
h3.api-title {
margin-top: 2em;
}
.api h3.api-title {
margin: 0;
overflow : auto;
}
.api h4 {
font-weight: normal;
font-style: italic;
margin-bottom: .25em;
text-decoration: underline;
margin-left: 20px;
}
.api dl {
margin-top: .25em;
}
.api dl.args {
margin-left: 40px;
}
.api dl.constants {
margin-left: 20px;
}
.api dt {
margin-top: 1em;
}
.api dt .name {
font-weight: bold;
}
.api dt .type {
margin-left: 15px;
font-size: .9em;
font-weight: 200;
color: black;
}
.api dd {
margin-bottom: 1em;
margin-left: 0;
}
.api .desc {
margin: 1em;
}
.api pre {
margin-right: 10px;
}
ol {
list-style: decimal;
padding-left: 30px;
margin-bottom: 1em;
}
.api-title .locus {
float: right;
font-weight: normal;
padding-right: 5px;
font-style: italic;
}
.api-title .subtext {
font-size: 11px;
text-align: left;
clear: both;
display: block;
font-weight: normal;
}
.api-title .subtext > code {
font-size: 11px;
margin-right: 12px;
}
.api-title .src-code {
color: #20338A !important;
border-bottom: none !important;
}
.or {
font-size: .9em;
text-decoration: underline;
font-style: italic;
}
#main pre {
margin: 1em 0;
}
#main a.selflink:link, #main a.selflink:visited, #main a.selflink:hover {
text-decoration: none;
border: none;
color: inherit;
background: none;
}
/** layout control **/
#menu-ico {
font-size: 30px;
float: right;
position: fixed;
top: 3px;
left: 6px;
}
#menu-ico.hidden {
display: none;
}
/** layout control **/
#menu-ico {
font-size: 30px;
float: right;
position: fixed;
top: 3px;
left: 6px;
}
#menu-ico.hidden {
display: none;
}
@nav-width: 270px;
@top-bar-height: 50px;
/* default to no sidebar */
.hidden {
display: none;
}
#nav {
display: block;
position: fixed;
width: @nav-width;
height: 100%;
top: 0;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.main-content {
position: absolute;
width: 100%;
top: @top-bar-height;
bottom: 0;
z-index: 1;
background: white;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
overflow-x: hidden;
margin-left: 0;
transition: margin-left 300ms ease-out;
}
.overlay {
margin-left: 0;
transition: margin-left 300ms ease-out, opacity 300ms ease-out;
opacity: 0;
background-color: rgba(0, 0, 0, 0.3);
}
#nav.show {
left: 0;
overflow: auto;
}
.github-ribbon {
display: none;
}
pre {
white-space: pre-wrap;
}
#main {
padding: 10px;
max-width: 700px;
}
.basic-or-full {
font-size: 1em;
margin: 10px 0;
}
#nav {
h1 {
margin-top: 1em;
font-size: 1.3em;
a {
text-decoration: none;
color: black;
&:hover {
background: none;
text-decoration: underline;
}
}
}
.logo {
width: 180px;
margin-bottom: 10px;
}
}
.top-bar {
position: absolute;
background: white;
width: 100%;
top: 0;
left: 0;
height: @top-bar-height;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
z-index: 2;
margin-left: 0;
transition: margin-left 300ms ease-out, opacity 300ms ease-out;
border-bottom: 1px solid #aaa;
.fa-bars {
font-size: 25px;
margin: 13px 10px 13px 20px;
}
h1 {
margin: 13px auto;
text-align: center;
font-size: 25px;
padding: 0;
margin-top: 8px;
.logo {
display: inline;
height: 1.1em;
vertical-align: baseline;
margin-bottom: 1px;
margin-right: 3px;
}
}
}
.sidebar-open {
overflow: hidden;
width: 100%;
position: absolute;
height: 100%;
.main-content {
margin-left: @nav-width;
}
.top-bar {
margin-left: @nav-width;
}
.overlay {
position: absolute;
margin-left: @nav-width;
width: 100%;
height: 100%;
z-index: 3;
opacity: 1;
}
}
@media (min-width: 768px) {
/* ipad portrait or better */
.main-content {
height: 100%;
margin-left: 0; /* nav width + padding */
padding-top: 0;
left: @nav-width;
right: 0;
width: auto;
border-left: 1px solid #ccc;
top: 0;
}
#nav {
display: block;
width: @nav-width;
position: fixed;
overflow: auto;
height: 100%;
top: 0;
left: 0;
}
.main-headline {
display: none;
}
#menu-ico {
display: none;
}
.overlay {
display: none;
}
.top-bar {
display: none;
}
#main {
padding: 30px;
}
.sidebar-open {
overflow: hidden;
width: 100%;
position: absolute;
height: 100%;
.main-content {
margin-left: 0;
}
.top-bar {
margin-left: 0;
}
.overlay {
display: none;
}
}
}
.complete-link {
font-size: 0.9em;
text-decoration: underline !important;
}
@media print {
body {
font-size: 10pt;
}
code, pre {
font-size: 8pt;
}
#nav {
display: none;
}
.main-content {
position: relative;
height: auto;
margin: 0;
left: 0;
top: 0;
}
.top-bar {
display: none;
}
}
.search-overlay {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 3;
background: white;
overflow: hidden;
.close-search {
float: right;
font-size: 2em;
.hotkey {
font-size: 0.6em;
color: #777;
vertical-align: middle;
}
text-decoration: none;
&:hover {
text-decoration: none;
background: none;
}
}
.search-box {
margin: 40px;
h3 {
font-size: 2em;
}
input {
font-size: 2em;
padding: 0.5em 0;
background: transparent;
border: none;
border-bottom: 2px solid #777;
width: 80%;
&:focus {
outline: 0;
}
}
}
.search-results {
margin: 40px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 170px;
overflow-y: scroll;
list-style: none;
padding: 0;
li {
font-size: 1em;
margin-bottom: 0.5em;
padding: 10px;
white-space: nowrap;
p {
margin: 0;
display: inline;
}
strong {
font-weight: bold;
}
&.selected {
background: yellow;
}
}
}
}
// This menu icon is inspired by
// http://www.codesynthesis.co.uk/code-snippets/create-a-hamburger-icon-with-css
@hamburger-icon-size: 18px;
// Make the target larger than the icon
.hamburger-menu-target {
height: @hamburger-icon-size;
width: @hamburger-icon-size;
padding: 19px 10px;
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
.hamburger-menu, .hamburger-menu:after, .hamburger-menu:before {
height: @hamburger-icon-size / 6;
width: @hamburger-icon-size;
background-color: #111;
border-radius: 10px;
position: relative;
}
.hamburger-menu:after, .hamburger-menu:before {
content: '';
position: absolute;
}
.hamburger-menu:after {
top: @hamburger-icon-size / 3;
}
.hamburger-menu:before {
top: @hamburger-icon-size / 1.5;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
table th, table td {
border: 1px solid #ddd;
padding: 5px 10px;
}
table th {
font-weight: bold;
text-align: left;
}
table tr:nth-child(even) {
background-color: #f8f8f8;
}

View File

@@ -1,31 +0,0 @@
{{#template name="api"}}
<h1 id="api">The Meteor API</h1>
Your JavaScript code can run in two environments: the *client* (browser), and
the *server* (a [Node.js](http://nodejs.org/) container on a server). For each
function in this API reference, we'll indicate if the function is available just
on the client, just on the server, or *Anywhere*.
{{> apiCore}}
{{> apiPubsub}}
{{> apiMethods}}
{{> apiCheck}}
{{> apiConnections}}
{{> apiCollections}}
{{> apiSession}}
{{> apiAccounts}}
{{> apiPasswords}}
{{> apiTemplates}}
{{> apiBlaze}}
{{> apiTimers}}
{{> apiTracker}}
{{> apiReactiveVar}}
{{> apiEjson}}
{{> apiHttp}}
{{> apiEmail}}
{{> apiAssets}}
{{> apiPackagejs}}
{{> apiMobileConfig}}
{{/template}}

View File

@@ -1,477 +0,0 @@
{{#template name="apiAccounts"}}
<h2 id="accounts_api"><span>Accounts</span></h2>
The Meteor Accounts system builds on top of the `userId` support in
[`publish`](#publish_userId) and [`methods`](#method_userId). The core
packages add the concept of user documents stored in the database, and
additional packages add [secure password
authentication](#accounts_passwords), [integration with third party
login services](#meteor_loginwithexternalservice), and a [pre-built user
interface](#accountsui).
The basic Accounts system is in the `accounts-base` package, but
applications typically include this automatically by adding one of the
login provider packages: `accounts-password`, `accounts-facebook`,
`accounts-github`, `accounts-google`, `accounts-meetup`,
`accounts-twitter`, or `accounts-weibo`.
Read more about customizing user accounts in the [Accounts](http://guide.meteor.com/accounts.html) article in the Meteor Guide.
{{> autoApiBox "Meteor.user"}}
Retrieves the user record for the current user from
the [`Meteor.users`](#meteor_users) collection.
On the client, this will be the subset of the fields in the document that
are published from the server (other fields won't be available on the
client). By default the server publishes `username`, `emails`, and
`profile` (writable by user). See [`Meteor.users`](#meteor_users) for more on
the fields used in user documents.
{{> autoApiBox "Meteor.userId"}}
{{> autoApiBox "Meteor.users"}}
This collection contains one document per registered user. Here's an example
user document:
{
_id: "bbca5d6a-2156-41c4-89da-0329e8c99a4f", // Meteor.userId()
username: "cool_kid_13", // unique name
emails: [
// each email address can only belong to one user.
{ address: "cool@example.com", verified: true },
{ address: "another@different.com", verified: false }
],
createdAt: Wed Aug 21 2013 15:16:52 GMT-0700 (PDT),
profile: {
// The profile is writable by the user by default.
name: "Joe Schmoe"
},
services: {
facebook: {
id: "709050", // facebook id
accessToken: "AAACCgdX7G2...AbV9AZDZD"
},
resume: {
loginTokens: [
{ token: "97e8c205-c7e4-47c9-9bea-8e2ccc0694cd",
when: 1349761684048 }
]
}
}
}
A user document can contain any data you want to store about a user. Meteor
treats the following fields specially:
- `username`: a unique String identifying the user.
- `emails`: an Array of Objects with keys `address` and `verified`;
an email address may belong to at most one user. `verified` is
a Boolean which is true if the user has [verified the
address](#accounts_verifyemail) with a token sent over email.
- `createdAt`: the Date at which the user document was created.
- `profile`: an Object which the user can create and update with any data.
Do not store anything on `profile` that you wouldn't want the user to edit
unless you have a deny rule on the `Meteor.users` collection.
- `services`: an Object containing data used by particular
login services. For example, its `reset` field contains
tokens used by [forgot password](#accounts_forgotpassword) links,
and its `resume` field contains tokens used to keep you
logged in between sessions.
Like all [Mongo.Collection](#collections)s, you can access all
documents on the server, but only those specifically published by the server are
available on the client.
By default, the current user's `username`, `emails` and `profile` are
published to the client. You can publish additional fields for the
current user with:
// server
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'other': 1, 'things': 1}});
} else {
this.ready();
}
});
// client
Meteor.subscribe("userData");
If the autopublish package is installed, information about all users
on the system is published to all clients. This includes `username`,
`profile`, and any fields in `services` that are meant to be public
(eg `services.facebook.id`,
`services.twitter.screenName`). Additionally, when using autopublish
more information is published for the currently logged in user,
including access tokens. This allows making API calls directly from
the client for services that allow this.
Users are by default allowed to specify their own `profile` field with
[`Accounts.createUser`](#accounts_createuser) and modify it with
`Meteor.users.update`. To allow users to edit additional fields, use
[`Meteor.users.allow`](#allow). To forbid users from making any modifications to
their user document:
Meteor.users.deny({update: function () { return true; }});
{{> autoApiBox "Meteor.loggingIn"}}
For example, [the `accounts-ui` package](#accountsui) uses this to display an
animation while the login request is being processed.
{{> autoApiBox "Meteor.logout"}}
{{> autoApiBox "Meteor.logoutOtherClients"}}
For example, when called in a user's browser, connections in that browser
remain logged in, but any other browsers or DDP clients logged in as that user
will be logged out.
{{> autoApiBox "Meteor.loginWithPassword"}}
If there are multiple users with a username or email only differing in case, a case sensitive match is required. Although `createUser` won't let you create users with ambiguous usernames or emails, this could happen with existing databases or if you modify the users collection directly.
This function is provided by the `accounts-password` package. See the
[Passwords](#accounts_passwords) section below.
{{> autoApiBox "Meteor.loginWith<ExternalService>"}}
Available functions are:
* `Meteor.loginWithMeteorDeveloperAccount`
* `Meteor.loginWithFacebook`
* `Meteor.loginWithGithub`
* `Meteor.loginWithGoogle`
* `Meteor.loginWithMeetup`
* `Meteor.loginWithTwitter`
* `Meteor.loginWithWeibo`
These functions initiate the login process with an external
service (eg: Facebook, Google, etc), using OAuth. When called they open a new pop-up
window that loads the provider's login page. Once the user has logged in
with the provider, the pop-up window is closed and the Meteor client
logs in to the Meteor server with the information provided by the external
service.
<a id="requestpermissions" name="requestpermissions"></a>
In addition to identifying the user to your application, some services
have APIs that allow you to take action on behalf of the user. To
request specific permissions from the user, pass the
`requestPermissions` option the login function. This will cause the user
to be presented with an additional page in the pop-up dialog to permit
access to their data. The user's `accessToken` &mdash; with permissions
to access the service's API &mdash; is stored in the `services` field of
the user document. The supported values for `requestPermissions` differ
for each login service and are documented on their respective developer
sites:
- Facebook: <http://developers.facebook.com/docs/authentication/permissions/>
- GitHub: <http://developer.github.com/v3/oauth/#scopes>
- Google: <https://developers.google.com/accounts/docs/OAuth2Login#scopeparameter>
- Meetup: <http://www.meetup.com/meetup_api/auth/#oauth2-scopes>
- Twitter, Weibo, Meteor developer accounts: `requestPermissions` currently not supported
External login services typically require registering and configuring
your application before use. The easiest way to do this is with the
[`accounts-ui` package](#accountsui) which presents a step-by-step guide
to configuring each service. However, the data can be also be entered
manually in the `ServiceConfiguration.configurations` collection, which
is exported by the `service-configuration` package.
First, add the service configuration package:
```bash
meteor add service-configuration
```
Then, in your app:
```js
ServiceConfiguration.configurations.upsert(
{ service: "weibo" },
{
$set: {
clientId: "1292962797",
loginStyle: "popup",
secret: "75a730b58f5691de5522789070c319bc"
}
}
);
```
Each external service has its own login provider package and login function. For
example, to support GitHub login, run in your terminal:
```bash
meteor add accounts-github
```
and use the `Meteor.loginWithGithub` function:
```javascript
Meteor.loginWithGithub({
requestPermissions: ['user', 'public_repo']
}, function (err) {
if (err)
Session.set('errorMessage', err.reason || 'Unknown error');
});
```
Login service configuration is sent from the server to the client over DDP when
your app starts up; you may not call the login function until the configuration
is loaded. The function `Accounts.loginServicesConfigured()` is a reactive data
source that will return true once the login service is configured; you should
not make login buttons visible or active until it is true.
Ensure that your [`$ROOT_URL`](#meteor_absoluteurl) matches the authorized
domain and callback URL that you configure with the external service (for
instance, if you are running Meteor behind a proxy server, `$ROOT_URL` should be
the externally-accessible URL, not the URL inside your proxy).
{{> autoApiBox "currentUser"}}
{{> autoApiBox "loggingIn"}}
{{> autoApiBox "Accounts.ui.config"}}
Example:
Accounts.ui.config({
requestPermissions: {
facebook: ['user_likes'],
github: ['user', 'repo']
},
requestOfflineToken: {
google: true
},
passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
});
<h2 id="advanced_accounts_api"><span>Accounts (multi-server)</span></h2>
The `accounts-base` package exports two constructors, called
`AccountsClient` and `AccountsServer`, which are used to create the
`Accounts` object that is available on the client and the server,
respectively.
This predefined `Accounts` object (along with similar convenience methods
of `Meteor`, such as [`Meteor.logout`](#meteor_logout)) is sufficient to
implement most accounts-related logic in Meteor apps. Nevertheless, these
two constructors can be instantiated more than once, to create multiple
independent connections between different accounts servers and their
clients, in more complicated authentication situations.
{{> autoApiBox "AccountsClient" }}
At most one of `options.connection` and `options.ddpUrl` should be
provided in any instantiation of `AccountsClient`. If neither is provided,
`Meteor.connection` will be used as the `.connection` property of the
`AccountsClient` instance.
Note that `AccountsClient` is currently available only on the client, due
to its use of browser APIs such as `window.localStorage`. In principle,
though, it might make sense to establish a client connection from one
server to another remote accounts server. Please [let us
know](https://github.com/meteor/meteor/wiki/Contributing-to-Meteor#feature-requests)
if you find yourself needing this server-to-server functionality.
{{> autoApiBox "AccountsServer" }}
The `AccountsClient` and `AccountsServer` classes share a common
superclass, `AccountsCommon`. Methods defined on
`AccountsCommon.prototype` will be available on both the client and the
server, via the predefined `Accounts` object (most common) or any custom
`accountsClientOrServer` object created using the `AccountsClient` or
`AccountsServer` constructors (less common).
Here are a few of those methods:
{{> autoApiBox "AccountsCommon#userId" }}
{{> autoApiBox "AccountsCommon#user" }}
{{> autoApiBox "AccountsCommon#config"}}
These methods are defined on `AccountsClient.prototype`, and are thus
available only on the client:
{{> autoApiBox "AccountsClient#loggingIn"}}
{{> autoApiBox "AccountsClient#logout"}}
{{> autoApiBox "AccountsClient#logoutOtherClients"}}
These methods are defined on `AccountsServer.prototype`, and are thus
available only on the server:
{{> autoApiBox "AccountsServer#validateNewUser"}}
This can be called multiple times. If any of the functions return `false` or
throw an error, the new user creation is aborted. To set a specific error
message (which will be displayed by [`accounts-ui`](#accountsui)), throw a new
[`Meteor.Error`](#meteor_error).
Example:
// Validate username, sending a specific error message on failure.
Accounts.validateNewUser(function (user) {
if (user.username && user.username.length >= 3)
return true;
throw new Meteor.Error(403, "Username must have at least 3 characters");
});
// Validate username, without a specific error message.
Accounts.validateNewUser(function (user) {
return user.username !== "root";
});
If the user is being created as part of a login attempt from a client (eg,
calling [`Accounts.createUser`](#accounts_createuser) from the client, or
[logging in for the first time with an external
service](#meteor_loginwithexternalservice)), these callbacks are called *before*
the [`Accounts.validateLoginAttempt`](#accounts_validateloginattempt)
callbacks. If these callbacks succeed but those fail, the user will still be
created but the connection will not be logged in as that user.
{{> autoApiBox "AccountsServer#onCreateUser"}}
Use this when you need to do more than simply accept or reject new user
creation. With this function you can programatically control the
contents of new user documents.
The function you pass will be called with two arguments: `options` and
`user`. The `options` argument comes
from [`Accounts.createUser`](#accounts_createuser) for
password-based users or from an external service login flow. `options` may come
from an untrusted client so make sure to validate any values you read from
it. The `user` argument is created on the server and contains a
proposed user object with all the automatically generated fields
required for the user to log in, including the `_id`.
The function should return the user document (either the one passed in or a
newly-created object) with whatever modifications are desired. The returned
document is inserted directly into the [`Meteor.users`](#meteor_users) collection.
The default create user function simply copies `options.profile` into
the new user document. Calling `onCreateUser` overrides the default
hook. This can only be called once.
Example:
<!-- XXX replace d6 with _.random once we have underscore 1.4.2 -->
// Support for playing D&D: Roll 3d6 for dexterity
Accounts.onCreateUser(function(options, user) {
var d6 = function () { return Math.floor(Random.fraction() * 6) + 1; };
user.dexterity = d6() + d6() + d6();
// We still want the default hook's 'profile' behavior.
if (options.profile)
user.profile = options.profile;
return user;
});
{{> autoApiBox "AccountsServer#validateLoginAttempt"}}
Call `validateLoginAttempt` with a callback to be called on login
attempts. It returns an object with a single method, `stop`. Calling
`stop()` unregisters the callback.
When a login attempt is made, the registered validate login callbacks
are called with a single argument, the attempt info object:
<dl class="objdesc">
{{#dtdd name="type" type="String"}}
The service name, such as "password" or "twitter".
{{/dtdd}}
{{#dtdd name="allowed" type="Boolean"}}
Whether this login is allowed and will be successful (if not aborted
by any of the validateLoginAttempt callbacks). False if the login
will not succeed (for example, an invalid password or the login was
aborted by a previous validateLoginAttempt callback).
{{/dtdd}}
{{#dtdd name="error" type="Exception"}}
When `allowed` is false, the exception describing why the login
failed. It will be a `Meteor.Error` for failures reported to the
user (such as invalid password), and can be a another kind of
exception for internal errors.
{{/dtdd}}
{{#dtdd name="user" type="Object"}}
When it is known which user was attempting to login, the Meteor user object.
This will always be present for successful logins.
{{/dtdd}}
{{#dtdd name="connection" type="Object"}}
The `connection` object the request came in on. See
[`Meteor.onConnection`](#meteor_onconnection) for details.
{{/dtdd}}
{{#dtdd name="methodName" type="String"}}
The name of the Meteor method being used to login.
{{/dtdd}}
{{#dtdd name="methodArguments" type="Array"}}
An array of the arguments passed to the login method.
{{/dtdd}}
</dl>
A validate login callback must return a truthy value for the login to
proceed. If the callback returns a falsy value or throws an
exception, the login is aborted. Throwing a `Meteor.Error` will
report the error reason to the user.
All registered validate login callbacks are called, even if one of the callbacks
aborts the login. The later callbacks will see the `allowed` field set to
`false` since the login will now not be successful. This allows later callbacks
to override an error from a previous callback; for example, you could override
the "Incorrect password" error with a different message.
Validate login callbacks that aren't explicitly trying to override a previous
error generally have no need to run if the attempt has already been determined
to fail, and should start with
if (!attempt.allowed)
return false;
{{> autoApiBox "AccountsCommon#onLogin"}}
See description of [AccountsCommon#onLoginFailure](#accounts_onloginfailure)
for details.
{{> autoApiBox "AccountsCommon#onLoginFailure"}}
Either the `onLogin` or the `onLoginFailure` callbacks will be called
for each login attempt. The `onLogin` callbacks are called after the
user has been successfully logged in. The `onLoginFailure` callbacks are
called after a login attempt is denied.
These functions return an object with a single method, `stop`. Calling
`stop()` unregisters the callback.
On the server, the callbacks get a single argument, the same attempt info
object as [`validateLoginAttempt`](#accounts_validateloginattempt). On the
client, no arguments are passed.
<h3 id="accounts_rate_limit"><span>Rate Limiting</span></h3>
By default, there are rules added to the [`DDPRateLimiter`](#ddpratelimiter)
that rate limit logins, new user registration and password reset calls to a
limit of 5 requests per 10 seconds per session. These are a basic solution
to dictionary attacks where a malicious user attempts to guess the passwords
of legitimate users by attempting all possible passwords.
These rate limiting rules can be removed by calling
`Accounts.removeDefaultRateLimit()`. Please see the
[`DDPRateLimiter`](#ddpratelimiter) docs for more information.
{{/template}}

View File

@@ -1,22 +0,0 @@
{{#template name="apiAssets"}}
<h2 id="assets"><span>Assets</span></h2>
`Assets` allows server code in a Meteor application to access static server
assets, which are located in the `private` subdirectory of an application's
tree. Assets are not processed as source files and are copied directly
into your application's bundle.
{{> autoApiBox "Assets.getText"}}
{{> autoApiBox "Assets.getBinary"}}
{{> autoApiBox "Assets.absoluteFilePath"}}
Static server assets are included by placing them in the application's `private`
subdirectory. For example, if an application's `private` subdirectory includes a
directory called `nested` with a file called `data.txt` inside it, then server
code can read `data.txt` by running:
var data = Assets.getText('nested/data.txt');
Note: Packages can only access their own assets. If you need to read the assets of a different package, or of the enclosing app, you need to get a reference to that package's `Assets` object.
{{/template}}

View File

@@ -1,308 +0,0 @@
{{#template name="apiBlaze"}}
<h2 id="blaze"><span>Blaze</span></h2>
Blaze is the package that makes reactive templates possible.
You can use the Blaze API directly in order to render templates programmatically
and manipulate "Views," the building blocks of reactive templates. For more
information, check out the [Blaze project page](https://www.meteor.com/blaze).
{{> autoApiBox "Blaze.render"}}
When you render a template, the callbacks added with
[`onCreated`](#template_onCreated) are invoked immediately, before evaluating
the content of the template. The callbacks added with
[`onRendered`](#template_onRendered) are invoked after the View is rendered and
inserted into the DOM.
The rendered template
will update reactively in response to data changes until the View is
removed using [`Blaze.remove`](#blaze_remove) or the View's
parent element is removed by Meteor or jQuery.
{{#warning}}
If the View is removed by some other mechanism
besides Meteor or jQuery (which Meteor integrates with by default),
the View may continue to update indefinitely. Most users will not need to
manually render templates and insert them into the DOM, but if you do,
be mindful to always call [`Blaze.remove`](#blaze_remove) when the View is
no longer needed.
{{/warning}}
{{> autoApiBox "Blaze.renderWithData"}}
`Blaze.renderWithData(Template.myTemplate, data)` is essentially the same as
`Blaze.render(Blaze.With(data, function () { return Template.myTemplate; }))`.
{{> autoApiBox "Blaze.remove"}}
Use `Blaze.remove` to remove a template or View previously inserted with
`Blaze.render`, in such a way that any behaviors attached to the DOM by
Meteor are cleaned up. The rendered template or View is now considered
["destroyed"](#template_onDestroyed), along with all nested templates and
Views. In addition, any data assigned via
jQuery to the DOM nodes is removed, as if the nodes were passed to
jQuery's `$(...).remove()`.
As mentioned in [`Blaze.render`](#blaze_render), it is important to "remove"
all content rendered via `Blaze.render` using `Blaze.remove`, unless the
parent node of `renderedView` is removed by a Meteor reactive
update or with jQuery.
`Blaze.remove` can be used even if the DOM nodes in question have already
been removed from the document, to tell Blaze to stop tracking and
updating these nodes.
{{> autoApiBox "Blaze.getData"}}
{{> autoApiBox "Blaze.toHTML"}}
Rendering a template to HTML loses all fine-grained reactivity. The
normal way to render a template is to either include it from another
template (`{{dstache}}> myTemplate}}`) or render and insert it
programmatically using `Blaze.render`. Only occasionally
is generating HTML useful.
Because `Blaze.toHTML` returns a string, it is not able to update the DOM
in response to reactive data changes. Instead, any reactive data
changes will invalidate the current Computation if there is one
(for example, an autorun that is the caller of `Blaze.toHTML`).
{{> autoApiBox "Blaze.toHTMLWithData"}}
{{> autoApiBox "Blaze.View"}}
Behind every template or part of a template &mdash; a template tag, say, like `{{dstache}}foo}}` or `{{dstache}}#if}}` &mdash; is
a View object, which is a reactively updating region of DOM.
Most applications do not need to be aware of these Views, but they offer a
way to understand and customize Meteor's rendering behavior for more
advanced applications and packages.
You can obtain a View object by calling [`Blaze.render`](#blaze_render) on a
template, or by accessing [`template.view`](#template_view) on a template
instance.
At the heart of a View is an [autorun](#tracker_autorun) that calls the View's
`renderFunction`, uses the result to create DOM nodes, and replaces the
contents of the View with these new DOM nodes. A View's content may consist
of any number of consecutive DOM nodes (though if it is zero, a placeholder
node such as a comment or an empty text node is automatically supplied). Any
reactive dependency established by `renderFunction` causes a full recalculation
of the View's contents when the dependency is invalidated. Templates, however,
are compiled in such a way that they do not have top-level dependencies and so
will only ever render once, while their parts may re-render many times.
When a `Blaze.View` is constructed by calling the constructor, no hooks
are fired and no rendering is performed. In particular, the View is
not yet considered to be "created." Only when the View is actually
used, by a call to `Blaze.render` or `Blaze.toHTML` or by inclusion in
another View, is it "created," right before it is rendered for the
first time. When a View is created, its `.parentView` is set if
appropriate, and then the `onViewCreated` hook is fired. The term
"unrendered View" means a newly constructed View that has not been
"created" or rendered.
The "current View" is kept in [`Blaze.currentView`](#blaze_currentview) and
is set during View rendering, callbacks, autoruns, and template event
handlers. It affects calls such as [`Template.currentData()`](#template_currentdata).
The following properties and methods are available on Blaze.View:
<dl class="objdesc">
{{#dtdd name="name" type="String" id="view_name"}}
The name of this type of View. View names may be used to identify
particular kinds of Views in code, but more often they simply aid in
debugging and comprehensibility of the View tree. Views generated
by Meteor have names like "Template.foo" and "if".
{{/dtdd}}
{{#dtdd name="parentView" type="View or null" id="view_parentview"}}
The enclosing View that caused this View to be rendered, if any.
{{/dtdd}}
{{#dtdd name="isCreated" type="Boolean" id="view_iscreated"}}
True if this View has been called on to be rendered by `Blaze.render`
or `Blaze.toHTML` or another View. Once it becomes true, never
becomes false again. A "created" View's `.parentView` has been
set to its final value. `isCreated` is set to true before
`onViewCreated` hooks are called.
{{/dtdd}}
{{#dtdd name="isRendered" type="Boolean" id="view_isrendered"}}
True if this View has been rendered to DOM by `Blaze.render` or
by the rendering of an enclosing View. Conversion to HTML by
`Blaze.toHTML` doesn't count. Once true, never becomes false.
{{/dtdd}}
{{#dtdd name="isDestroyed" type="Boolean" id="view_isdestroyed"}}
True if this View has been destroyed, such as by `Blaze.remove()` or
by a reactive update that removes it. A destroyed View's autoruns
have been stopped, and its DOM nodes have generally been cleaned
of all Meteor reactivity and possibly dismantled.
{{/dtdd}}
{{#dtdd name="renderCount" type="Integer" id="view_rendercount"}}
The number of times the View has been rendered, including the
current time if the View is in the process of being rendered
or re-rendered.
{{/dtdd}}
{{#dtdd name="autorun(runFunc)" id="view_autorun"}}
Like [`Tracker.autorun`](#tracker_autorun), except that the autorun is
automatically stopped when the View is destroyed, and the
[current View](#blaze_currentview) is always set when running `runFunc`.
There is no relationship to the View's internal autorun or render
cycle. In `runFunc`, the View is bound to `this`.
{{/dtdd}}
{{#dtdd name="onViewCreated(func)" id="view_onviewcreated"}}
If the View hasn't been created yet, calls `func` when the View
is created. In `func`, the View is bound to `this`.
This hook is the basis for the [`created`](#template_created)
template callback.
{{/dtdd}}
{{#dtdd name="onViewReady(func)" id="view_onviewready"}}
Calls `func` when the View is rendered and inserted into the DOM,
after waiting for the end of
[flush time](#tracker_afterflush). Does not fire if the View
is destroyed at any point before it would fire.
May fire multiple times (if the View re-renders).
In `func`, the View is bound to `this`.
This hook is the basis for the [`rendered`](#template_rendered)
template callback.
{{/dtdd}}
{{#dtdd name="onViewDestroyed(func)" id="view_onviewdestroyed"}}
If the View hasn't been destroyed yet, calls `func` when the
View is destroyed. A View may be destroyed without ever becoming
"ready." In `func`, the View is bound to `this`.
This hook is the basis for the [`destroyed`](#template_destroyed)
template callback.
{{/dtdd}}
{{#dtdd name="firstNode()" type="DOM node" id="view_firstnode"}}
The first node of the View's rendered content. Note that this may
be a text node. Requires that the View be rendered.
If the View rendered to zero DOM nodes, it may be a placeholder
node (comment or text node). The DOM extent of a View consists
of the nodes between `view.firstNode()` and `view.lastNode()`,
inclusive.
{{/dtdd}}
{{#dtdd name="lastNode()" type="DOM node" id="view_lastnode"}}
The last node of the View's rendered content.
See [`firstNode()`](#view_firstnode).
{{/dtdd}}
{{#dtdd name="template" type="Template" id="view_template"}}
For Views created by invoking templates, the original Template
object. For example, `Blaze.render(Template.foo).template === Template.foo`.
{{/dtdd}}
{{#dtdd name="templateInstance()" type="Template instance"
id="view_templateinstance"}} For Views created by invoking templates,
returns the [template instance](#template_inst) object for this
particular View. For example, in a [`created`](#template_created)
callback, `this.view.templateInstance() === this`.
Template instance objects have fields like `data`, `firstNode`, and
`lastNode` which are not reactive and which are also not automatically
kept up to date. Calling `templateInstance()` causes these fields to
be updated.
{{/dtdd}}
</dl>
{{> autoApiBox "Blaze.currentView"}}
The "current view" is used by [`Template.currentData()`](#template_currentdata) and
[`Template.instance()`](#template_instance) to determine
the contextually relevant data context and template instance.
{{> autoApiBox "Blaze.getView"}}
If you don't specify an `element`, there must be a current View or an
error will be thrown. This is in contrast to
[`Blaze.currentView`](#blaze_currentview).
{{> autoApiBox "Blaze.With"}}
Returns an unrendered View object you can pass to `Blaze.render`.
Unlike `{{dstache}}#with}}` (as used in templates), `Blaze.With` has no "else" case, and
a falsy value for the data context will not prevent the content from
rendering.
{{> autoApiBox "Blaze.If"}}
Returns an unrendered View object you can pass to `Blaze.render`.
Matches the behavior of `{{dstache}}#if}}` in templates.
{{> autoApiBox "Blaze.Unless"}}
Returns an unrendered View object you can pass to `Blaze.render`.
Matches the behavior of `{{dstache}}#unless}}` in templates.
{{> autoApiBox "Blaze.Each"}}
Returns an unrendered View object you can pass to `Blaze.render`.
Matches the behavior of `{{dstache}}#each}}` in templates.
{{> autoApiBox "Blaze.Template"}}
Templates defined by the template compiler, such as `Template.myTemplate`,
are objects of type `Blaze.Template` (aliased as `Template`).
In addition to methods like `events` and `helpers`, documented as part of
the [Template API](#templates_api), the following fields and methods are
present on template objects:
<dl class="objdesc">
{{#dtdd name="viewName" type="String" id="template_viewname"}}
Same as the constructor argument.
{{/dtdd}}
{{#dtdd name="renderFunction" type="Function" id="template_renderfunction"}}
Same as the constructor argument.
{{/dtdd}}
{{#dtdd name="constructView()" id="template_constructview"}}
Constructs and returns an unrendered View object. This method is invoked
by Meteor whenever the template is used, such as by `Blaze.render` or by
`{{dstache}}> foo}}` where `foo` resolves to a Template object.
`constructView()` constructs a View using `viewName` and `renderFunction`
as constructor arguments, and then configures it as a template
View, setting up `view.template`, `view.templateInstance()`, event maps, and so on.
{{/dtdd}}
</dl>
{{> autoApiBox "Blaze.isTemplate"}}
{{> apiBoxTitle name="Renderable Content" id="renderable_content"}}
A value is *renderable content* if it is one of the following:
* A [template object](#templates_api) like `Template.myTemplate`
* An unrendered [View](#blaze_view) object, like the return value of `Blaze.With`
* `null` or `undefined`
{{#note}}
Internally, renderable content includes objects representing HTML tags
as well, but these objects are not yet part of the officially-supported,
public API.
{{/note}}
{{/template}}

View File

@@ -1,154 +0,0 @@
{{#template name="apiCheck"}}
<h2 id="check_package"><span>Check</span></h2>
The `check` package includes pattern checking functions useful for checking the types and structure
of variables and an [extensible library of patterns](#matchpatterns) to specify which types you are
expecting.
{{> autoApiBox "check"}}
Meteor methods and publish functions can take arbitrary [EJSON](#ejson) types as arguments, but most
functions expect their arguments to be of a particular type. `check` is a lightweight function for
checking that arguments and other values are of the expected type. For example:
```js
Meteor.publish("chats-in-room", function (roomId) {
// Make sure roomId is a string, not an arbitrary mongo selector object.
check(roomId, String);
return Chats.find({room: roomId});
});
Meteor.methods({addChat: function (roomId, message) {
check(roomId, String);
check(message, {
text: String,
timestamp: Date,
// Optional, but if present must be an array of strings.
tags: Match.Maybe([String])
});
// ... do something with the message ...
}});
```
If the match fails, `check` throws a `Match.Error` describing how it failed. If
this error gets sent over the wire to the client, it will appear only as
`Meteor.Error(400, "Match Failed")`. The failure details will be written to the
server logs but not revealed to the client.
{{> autoApiBox "Match.test"}}
`Match.test` can be used to identify if a variable has a certain structure.
```js
// will return true for {foo: 1, bar: "hello"} or similar
Match.test(value, {foo: Match.Integer, bar: String});
// will return true if value is a string
Match.test(value, String);
// will return true if value is a String or an array of Numbers
Match.test(value, Match.OneOf(String, [Number]));
```
This can be useful if you have a function that accepts several different kinds
of objects, and you want to determine which was passed in.
{{> apiBoxTitle name="Match Patterns" id="matchpatterns"}}
The following patterns can be used as pattern arguments to
[`check`](#check) and `Match.test`:
<dl>
{{#dtdd "<code>Match.Any</code>"}}
Matches any value.
{{/dtdd}}
{{#dtdd "<code>String</code>, <code>Number</code>, <code>Boolean</code>, <code>undefined</code>, <code>null</code>"}}
Matches a primitive of the given type.
{{/dtdd}}
{{#dtdd "<code>Match.Integer</code>"}}
Matches a signed 32-bit integer. Doesn't match `Infinity`, `-Infinity`, or `NaN`.
{{/dtdd}}
{{#dtdd "<code>[<em>pattern</em>]</code>"}}
A one-element array matches an array of elements, each of which match
*pattern*. For example, `[Number]` matches a (possibly empty) array of numbers;
`[Match.Any]` matches any array.
{{/dtdd}}
{{#dtdd "<code>{<em>key1</em>: <em>pattern1</em>, <em>key2</em>: <em>pattern2</em>, ...}</code>"}}
Matches an Object with the given keys, with values matching the given patterns.
If any *pattern* is a `Match.Maybe` or `Match.Optional`, that key does not need to exist
in the object. The value may not contain any keys not listed in the pattern.
The value must be a plain Object with no special prototype.
{{/dtdd}}
{{#dtdd "<code>Match.ObjectIncluding({<em>key1</em>: <em>pattern1</em>, <em>key2</em>: <em>pattern2</em>, ...})</code>"}}
Matches an Object with the given keys; the value may also have other keys
with arbitrary values.
{{/dtdd}}
{{#dtdd "<code>Object</code>"}}
Matches any plain Object with any keys; equivalent to
`Match.ObjectIncluding({})`.
{{/dtdd}}
{{#dtdd "<code>Match.Maybe(<em>pattern</em>)</code>"}}
Matches either `undefined`, `null`, or _pattern_. If used in an object, matches only if the key is
not set as opposed to the value being set to `undefined` or `null`. This set of conditions was
chosen because `undefined` arguments to Meteor Methods are converted to `null` when sent over the
wire.
```js
// In an object
var pattern = { name: Match.Maybe(String) };
check({ name: "something" }, pattern) // OK
check({}, pattern) // OK
check({ name: undefined }, pattern) // Throws an exception
check({ name: null }, pattern) // Throws an exception
// Outside an object
check(null, Match.Maybe(String)); // OK
check(undefined, Match.Maybe(String)); // OK
```
{{/dtdd}}
{{#dtdd "<code>Match.Optional(<em>pattern</em>)</code>"}}
Behaves like `Match.Maybe` except it doesn't accept `null`. If used in an object, the behavior is
identical to `Match.Maybe`.
{{/dtdd}}
{{#dtdd "<code>Match.OneOf(<em>pattern1</em>, <em>pattern2</em>, ...)</code>"}}
Matches any value that matches at least one of the provided patterns.
{{/dtdd}}
{{#dtdd "Any constructor function (eg, <code>Date</code>)"}}
Matches any element that is an instance of that type.
{{/dtdd}}
{{#dtdd "<code>Match.Where(<em>condition</em>)</code>"}}
Calls the function *condition* with the value as the argument. If *condition*
returns true, this matches. If *condition* throws a `Match.Error` or returns
false, this fails. If *condition* throws any other error, that error is thrown
from the call to `check` or `Match.test`. Examples:
check(buffer, Match.Where(EJSON.isBinary));
NonEmptyString = Match.Where(function (x) {
check(x, String);
return x.length > 0;
});
check(arg, NonEmptyString);
{{/dtdd}}
</dl>
{{/template}}

View File

@@ -1,865 +0,0 @@
{{#template name="apiCollections"}}
<h2 id="collections"><span>Collections</span></h2>
Meteor stores data in *collections*. To get started, declare a
collection with `new Mongo.Collection`.
{{> autoApiBox "Mongo.Collection"}}
Calling this function is analogous to declaring a model in a traditional ORM
(Object-Relation Mapper)-centric framework. It sets up a *collection* (a storage
space for records, or "documents") that can be used to store a particular type
of information, like users, posts, scores, todo items, or whatever matters to
your application. Each document is a EJSON object. It includes an `_id`
property whose value is unique in the collection, which Meteor will set when you
first create the document.
// common code on client and server declares a DDP-managed mongo
// collection.
Chatrooms = new Mongo.Collection("chatrooms");
Messages = new Mongo.Collection("messages");
The function returns an object with methods to [`insert`](#insert)
documents in the collection, [`update`](#update) their properties, and
[`remove`](#remove) them, and to [`find`](#find) the documents in the
collection that match arbitrary criteria. The way these methods work is
compatible with the popular Mongo database API. The same database API
works on both the client and the server (see below).
// return array of my messages
var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch();
// create a new message
Messages.insert({text: "Hello, world!"});
// mark my first message as "important"
Messages.update(myMessages[0]._id, {$set: {important: true}});
If you pass a `name` when you create the collection, then you are
declaring a persistent collection &mdash; one that is stored on the
server and seen by all users. Client code and server code can both
access the same collection using the same API.
Specifically, when you pass a `name`, here's what happens:
* On the server (if you do not specify a `connection`), a collection with that
name is created on a backend Mongo server. When you call methods on that
collection on the server, they translate directly into normal Mongo operations
(after checking that they match your [access control rules](#allow)).
* On the client (and on the server if you specify a `connection`), a Minimongo
instance is created. Minimongo is essentially an in-memory, non-persistent
implementation of Mongo in pure JavaScript. It serves as a local cache that
stores just the subset of the database that this client is working with. Queries
([`find`](#find)) on these collections are served directly out of this cache,
without talking to the server.
* When you write to the database on the client ([`insert`](#insert),
[`update`](#update), [`remove`](#remove)), the command is executed locally
immediately, and, simultaneously, it's sent to the server and executed
there too. This happens via [stubs](#meteor_methods), because writes are
implemented as methods.
{{#note}}
When, on the server, you write to a collection which has a specified
`connection` to another server, it sends the corresponding method to the other
server and receives the changed values back from it over DDP. Unlike on the
client, it does not execute the write locally first.
{{/note}}
If you pass `null` as the `name`, then you're creating a local
collection. It's not synchronized anywhere; it's just a local scratchpad
that supports Mongo-style [`find`](#find), [`insert`](#insert),
[`update`](#update), and [`remove`](#remove) operations. (On both the
client and the server, this scratchpad is implemented using Minimongo.)
By default, Meteor automatically publishes every document in your
collection to each connected client. To turn this behavior off, remove
the `autopublish` package, in your terminal:
```bash
meteor remove autopublish
```
and instead call [`Meteor.publish`](#meteor_publish) to specify which parts of
your collection should be published to which users.
```js
// Create a collection called Posts and put a document in it. The
// document will be immediately visible in the local copy of the
// collection. It will be written to the server-side database
// a fraction of a second later, and a fraction of a second
// after that, it will be synchronized down to any other clients
// that are subscribed to a query that includes it (see
// Meteor.subscribe and autopublish)
Posts = new Mongo.Collection("posts");
Posts.insert({title: "Hello world", body: "First post"});
// Changes are visible immediately -- no waiting for a round trip to
// the server.
assert(Posts.find().count() === 1);
// Create a temporary, local collection. It works just like any other
// collection, but it doesn't send changes to the server, and it
// can't receive any data from subscriptions.
Scratchpad = new Mongo.Collection;
for (var i = 0; i < 10; i++)
Scratchpad.insert({number: i * 2});
assert(Scratchpad.find({number: {$lt: 9}}).count() === 5);
```
Generally, you'll assign `Mongo.Collection` objects in your app to global
variables. You can only create one `Mongo.Collection` object for each
underlying Mongo collection.
If you specify a `transform` option to the `Collection` or any of its retrieval
methods, documents are passed through the `transform` function before being
returned or passed to callbacks. This allows you to add methods or otherwise
modify the contents of your collection from their database representation. You
can also specify `transform` on a particular `find`, `findOne`, `allow`, or
`deny` call. Transform functions must return an object and they may not change
the value of the document's `_id` field (though it's OK to leave it out).
// An Animal class that takes a document in its constructor
Animal = function (doc) {
_.extend(this, doc);
};
_.extend(Animal.prototype, {
makeNoise: function () {
console.log(this.sound);
}
});
// Define a Collection that uses Animal as its document
Animals = new Mongo.Collection("Animals", {
transform: function (doc) { return new Animal(doc); }
});
// Create an Animal and call its makeNoise method
Animals.insert({name: "raptor", sound: "roar"});
Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"
`transform` functions are not called reactively. If you want to add a
dynamically changing attribute to an object, do it with a function that computes
the value at the time it's called, not by computing the attribute at `transform`
time.
{{#warning}}
In this release, Minimongo has some limitations:
* `$pull` in modifiers can only accept certain kinds
of selectors.
* `findAndModify`, aggregate functions, and
map/reduce aren't supported.
All of these will be addressed in a future release. For full
Minimongo release notes, see packages/minimongo/NOTES
in the repository.
{{/warning}}
{{#warning}}
Minimongo doesn't currently have indexes. It's rare for this to be an
issue, since it's unusual for a client to have enough data that an
index is worthwhile.
{{/warning}}
Read more about collections and how to use them in the [Collections](http://guide.meteor.com/collections.html) article in the Meteor Guide.
{{> autoApiBox "Mongo.Collection#find"}}
`find` returns a cursor. It does not immediately access the database or return
documents. Cursors provide `fetch` to return all matching documents, `map` and
`forEach` to iterate over all matching documents, and `observe` and
`observeChanges` to register callbacks when the set of matching documents
changes.
{{#warning}}
Collection cursors are not query snapshots. If the database changes
between calling `Collection.find` and fetching the
results of the cursor, or while fetching results from the cursor,
those changes may or may not appear in the result set.
{{/warning}}
Cursors are a reactive data source. On the client, the first time you retrieve a
cursor's documents with `fetch`, `map`, or `forEach` inside a
reactive computation (eg, a template or
[`autorun`](#tracker_autorun)), Meteor will register a
dependency on the underlying data. Any change to the collection that
changes the documents in a cursor will trigger a recomputation. To
disable this behavior, pass `{reactive: false}` as an option to
`find`.
Note that when `fields` are specified, only changes to the included
fields will trigger callbacks in `observe`, `observeChanges` and
invalidations in reactive computations using this cursor. Careful use
of `fields` allows for more fine-grained reactivity for computations
that don't depend on an entire document.
{{> autoApiBox "Mongo.Collection#findOne"}}
Equivalent to `find(selector, options).fetch()[0]` with
`options.limit = 1`.
{{> autoApiBox "Mongo.Collection#insert"}}
Add a document to the collection. A document is just an object, and
its fields can contain any combination of EJSON-compatible datatypes
(arrays, objects, numbers, strings, `null`, true, and false).
`insert` will generate a unique ID for the object you pass, insert it
in the database, and return the ID. When `insert` is called from
untrusted client code, it will be allowed only if passes any
applicable [`allow`](#allow) and [`deny`](#deny) rules.
On the server, if you don't provide a callback, then `insert` blocks
until the database acknowledges the write, or throws an exception if
something went wrong. If you do provide a callback, `insert` still
returns the ID immediately. Once the insert completes (or fails), the
callback is called with error and result arguments. In an error case,
`result` is undefined. If the insert is successful, `error` is
undefined and `result` is the new document ID.
On the client, `insert` never blocks. If you do not provide a callback
and the insert fails on the server, then Meteor will log a warning to
the console. If you provide a callback, Meteor will call that function
with `error` and `result` arguments. In an error case, `result` is
undefined. If the insert is successful, `error` is undefined and
`result` is the new document ID.
Example:
var groceriesId = Lists.insert({name: "Groceries"});
Items.insert({list: groceriesId, name: "Watercress"});
Items.insert({list: groceriesId, name: "Persimmons"});
{{> autoApiBox "Mongo.Collection#update"}}
Modify documents that match `selector` according to `modifier` (see
[modifier documentation](#modifiers)).
The behavior of `update` differs depending on whether it is called by
trusted or untrusted code. Trusted code includes server code and
method code. Untrusted code includes client-side code such as event
handlers and a browser's JavaScript console.
- Trusted code can modify multiple documents at once by setting
`multi` to true, and can use an arbitrary [Mongo
selector](#selectors) to find the documents to modify. It bypasses
any access control rules set up by [`allow`](#allow) and
[`deny`](#deny). The number of affected documents will be returned
from the `update` call if you don't pass a callback.
- Untrusted code can only modify a single document at once, specified
by its `_id`. The modification is allowed only after checking any
applicable [`allow`](#allow) and [`deny`](#deny) rules. The number
of affected documents will be returned to the callback. Untrusted
code cannot perform upserts, except in insecure mode.
On the server, if you don't provide a callback, then `update` blocks
until the database acknowledges the write, or throws an exception if
something went wrong. If you do provide a callback, `update` returns
immediately. Once the update completes, the callback is called with a
single error argument in the case of failure, or a second argument
indicating the number of affected documents if the update was successful.
On the client, `update` never blocks. If you do not provide a callback
and the update fails on the server, then Meteor will log a warning to
the console. If you provide a callback, Meteor will call that function
with an error argument if there was an error, or a second argument
indicating the number of affected documents if the update was successful.
Client example:
// When the givePoints button in the admin dashboard is pressed,
// give 5 points to the current player. The new score will be
// immediately visible on everyone's screens.
Template.adminDashboard.events({
'click .givePoints': function () {
Players.update(Session.get("currentPlayer"), {$inc: {score: 5}});
}
});
Server example:
// Give the "Winner" badge to each user with a score greater than
// 10. If they are logged in and their badge list is visible on the
// screen, it will update automatically as they watch.
Meteor.methods({
declareWinners: function () {
Players.update({score: {$gt: 10}},
{$addToSet: {badges: "Winner"}},
{multi: true});
}
});
You can use `update` to perform a Mongo upsert by setting the `upsert`
option to true. You can also use the [`upsert`](#upsert) method to perform an
upsert that returns the _id of the document that was inserted (if there was one)
in addition to the number of affected documents.
{{> autoApiBox "Mongo.Collection#upsert"}}
Modify documents that match `selector` according to `modifier`, or insert
a document if no documents were modified. `upsert` is the same as calling
`update` with the `upsert` option set to true, except that the return
value of `upsert` is an object that contain the keys `numberAffected`
and `insertedId`. (`update` returns only the number of affected documents.)
{{> autoApiBox "Mongo.Collection#remove"}}
Find all of the documents that match `selector` and delete them from
the collection.
The behavior of `remove` differs depending on whether it is called by
trusted or untrusted code. Trusted code includes server code and
method code. Untrusted code includes client-side code such as event
handlers and a browser's JavaScript console.
- Trusted code can use an arbitrary [Mongo selector](#selectors) to
find the documents to remove, and can remove more than one document
at once by passing a selector that matches multiple documents. It
bypasses any access control rules set up by [`allow`](#allow) and
[`deny`](#deny). The number of removed documents will be returned
from `remove` if you don't pass a callback.
As a safety measure, if `selector` is omitted (or is `undefined`),
no documents will be removed. Set `selector` to `{}` if you really
want to remove all documents from your collection.
- Untrusted code can only remove a single document at a time,
specified by its `_id`. The document is removed only after checking
any applicable [`allow`](#allow) and [`deny`](#deny) rules. The
number of removed documents will be returned to the callback.
On the server, if you don't provide a callback, then `remove` blocks
until the database acknowledges the write and then returns the number
of removed documents, or throws an exception if
something went wrong. If you do provide a callback, `remove` returns
immediately. Once the remove completes, the callback is called with a
single error argument in the case of failure, or a second argument
indicating the number of removed documents if the remove was successful.
On the client, `remove` never blocks. If you do not provide a callback
and the remove fails on the server, then Meteor will log a warning to the
console. If you provide a callback, Meteor will call that function with an
error argument if there was an error, or a second argument indicating the number
of removed documents if the remove was successful.
Client example:
// When the remove button is clicked on a chat message, delete
// that message.
Template.chat.events({
'click .remove': function () {
Messages.remove(this._id);
}
});
Server example:
// When the server starts, clear the log, and delete all players
// with a karma of less than -2.
Meteor.startup(function () {
if (Meteor.isServer) {
Logs.remove({});
Players.remove({karma: {$lt: -2}});
}
});
{{> autoApiBox "Mongo.Collection#allow"}}
When a client calls `insert`, `update`, or `remove` on a collection, the
collection's `allow` and [`deny`](#deny) callbacks are called
on the server to determine if the write should be allowed. If at least
one `allow` callback allows the write, and no `deny` callbacks deny the
write, then the write is allowed to proceed.
These checks are run only when a client tries to write to the database
directly, for example by calling `update` from inside an event
handler. Server code is trusted and isn't subject to `allow` and `deny`
restrictions. That includes methods that are called with `Meteor.call`
&mdash; they are expected to do their own access checking rather than
relying on `allow` and `deny`.
You can call `allow` as many times as you like, and each call can
include any combination of `insert`, `update`, and `remove`
functions. The functions should return `true` if they think the
operation should be allowed. Otherwise they should return `false`, or
nothing at all (`undefined`). In that case Meteor will continue
searching through any other `allow` rules on the collection.
The available callbacks are:
<dl class="callbacks">
{{#dtdd "insert(userId, doc)"}}
The user `userId` wants to insert the document `doc` into the
collection. Return `true` if this should be allowed.
`doc` will contain the `_id` field if one was explicitly set by the client, or
if there is an active `transform`. You can use this to prevent users from
specifying arbitrary `_id` fields.
{{/dtdd}}
{{#dtdd "update(userId, doc, fieldNames, modifier)"}}
The user `userId` wants to update a document `doc`. (`doc` is the
current version of the document from the database, without the
proposed update.) Return `true` to permit the change.
`fieldNames` is an array of the (top-level) fields in `doc` that the
client wants to modify, for example
`['name',`&nbsp;`'score']`.
`modifier` is the raw Mongo modifier that
the client wants to execute; for example,
`{$set: {'name.first': "Alice"}, $inc: {score: 1}}`.
Only Mongo modifiers are supported (operations like `$set` and `$push`).
If the user tries to replace the entire document rather than use
$-modifiers, the request will be denied without checking the `allow`
functions.
{{/dtdd}}
{{#dtdd "remove(userId, doc)"}}
The user `userId` wants to remove `doc` from the database. Return
`true` to permit this.
{{/dtdd}}
</dl>
When calling `update` or `remove` Meteor will by default fetch the
entire document `doc` from the database. If you have large documents
you may wish to fetch only the fields that are actually used by your
functions. Accomplish this by setting `fetch` to an array of field
names to retrieve.
Example:
```js
// Create a collection where users can only modify documents that
// they own. Ownership is tracked by an 'owner' field on each
// document. All documents must be owned by the user that created
// them and ownership can't be changed. Only a document's owner
// is allowed to delete it, and the 'locked' attribute can be
// set on a document to prevent its accidental deletion.
Posts = new Mongo.Collection("posts");
Posts.allow({
insert: function (userId, doc) {
// the user must be logged in, and the document must be owned by the user
return (userId && doc.owner === userId);
},
update: function (userId, doc, fields, modifier) {
// can only change your own documents
return doc.owner === userId;
},
remove: function (userId, doc) {
// can only remove your own documents
return doc.owner === userId;
},
fetch: ['owner']
});
Posts.deny({
update: function (userId, doc, fields, modifier) {
// can't change owners
return _.contains(fields, 'owner');
},
remove: function (userId, doc) {
// can't remove locked documents
return doc.locked;
},
fetch: ['locked'] // no need to fetch 'owner'
});
```
If you never set up any `allow` rules on a collection then all client
writes to the collection will be denied, and it will only be possible to
write to the collection from server-side code. In this case you will
have to create a method for each possible write that clients are allowed
to do. You'll then call these methods with `Meteor.call` rather than
having the clients call `insert`, `update`, and `remove` directly on the
collection.
Meteor also has a special "insecure mode" for quickly prototyping new
applications. In insecure mode, if you haven't set up any `allow` or `deny`
rules on a collection, then all users have full write access to the
collection. This is the only effect of insecure mode. If you call `allow` or
`deny` at all on a collection, even `Posts.allow({})`, then access is checked
just like normal on that collection. __New Meteor projects start in insecure
mode by default.__ To turn it off just run in your terminal:
```bash
meteor remove insecure
```
{{> autoApiBox "Mongo.Collection#deny"}}
This works just like [`allow`](#allow), except it lets you
make sure that certain writes are definitely denied, even if there is an
`allow` rule that says that they should be permitted.
When a client tries to write to a collection, the Meteor server first
checks the collection's `deny` rules. If none of them return true then
it checks the collection's `allow` rules. Meteor allows the write only
if no `deny` rules return `true` and at least one `allow` rule returns
`true`.
{{> autoApiBox "Mongo.Collection#rawCollection"}}
{{> autoApiBox "Mongo.Collection#rawDatabase"}}
<h2 id="mongo_cursor"><span>Cursors</span></h2>
To create a cursor, use [`find`](#find). To access the documents in a
cursor, use [`forEach`](#foreach), [`map`](#map), or [`fetch`](#fetch).
{{> autoApiBox "Mongo.Cursor#forEach"}}
This interface is compatible with [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).
When called from a reactive computation, `forEach` registers dependencies on
the matching documents.
Examples:
// Print the titles of the five top-scoring posts
var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5});
var count = 0;
topPosts.forEach(function (post) {
console.log("Title of post " + count + ": " + post.title);
count += 1;
});
{{> autoApiBox "Mongo.Cursor#map"}}
This interface is compatible with [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
When called from a reactive computation, `map` registers dependencies on
the matching documents.
<!-- The following is not yet implemented, but users shouldn't assume
sequential execution anyway because that will break. -->
On the server, if `callback` yields, other calls to `callback` may occur while
the first call is waiting. If strict sequential execution is necessary, use
`forEach` instead.
{{> autoApiBox "Mongo.Cursor#fetch"}}
When called from a reactive computation, `fetch` registers dependencies on
the matching documents.
{{> autoApiBox "Mongo.Cursor#count"}}
Unlike the other functions, `count` registers a dependency only on the
number of matching documents. (Updates that just change or reorder the
documents in the result set will not trigger a recomputation.)
{{> autoApiBox "Mongo.Cursor#observe"}}
Establishes a *live query* that invokes callbacks when the result of
the query changes. The callbacks receive the entire contents of the
document that was affected, as well as its old contents, if
applicable. If you only need to receive the fields that changed, see
[`observeChanges`](#observe_changes).
`callbacks` may have the following functions as properties:
<dl class="callbacks">
<dt><span class="name">added(document)</span> <span class="or">or</span></dt>
<dt><span class="name">addedAt(document, atIndex, before)</span></dt>
<dd>
{{#markdown}}
A new document `document` entered the result set. The new document
appears at position `atIndex`. It is immediately before the document
whose `_id` is `before`. `before` will be `null` if the new document
is at the end of the results.
{{/markdown}}
</dd>
<dt><span class="name">changed(newDocument, oldDocument)
<span class="or">or</span></span></dt>
<dt><span class="name">changedAt(newDocument, oldDocument, atIndex)</span></dt>
<dd>
{{#markdown}}
The contents of a document were previously `oldDocument` and are now
`newDocument`. The position of the changed document is `atIndex`.
{{/markdown}}
</dd>
<dt><span class="name">removed(oldDocument)</span>
<span class="or">or</span></dt>
<dt><span class="name">removedAt(oldDocument, atIndex)</span></dt>
<dd>
{{#markdown}}
The document `oldDocument` is no longer in the result set. It used to be at position `atIndex`.
{{/markdown}}
</dd>
{{#dtdd "movedTo(document, fromIndex, toIndex, before)"}}
A document changed its position in the result set, from `fromIndex` to `toIndex`
(which is before the document with id `before`). Its current contents is
`document`.
{{/dtdd}}
</dl>
Use `added`, `changed`, and `removed` when you don't care about the
order of the documents in the result set. They are more efficient than
`addedAt`, `changedAt`, and `removedAt`.
Before `observe` returns, `added` (or `addedAt`) will be called zero
or more times to deliver the initial results of the query.
`observe` returns a live query handle, which is an object with a `stop` method.
Call `stop` with no arguments to stop calling the callback functions and tear
down the query. **The query will run forever until you call this.** If
`observe` is called from a `Tracker.autorun` computation, it is automatically
stopped when the computation is rerun or stopped.
(If the cursor was created with the option `reactive` set to false, it will
only deliver the initial results and will not call any further callbacks;
it is not necessary to call `stop` on the handle.)
{{> autoApiBox "Mongo.Cursor#observeChanges"}}
Establishes a *live query* that invokes callbacks when the result of
the query changes. In contrast to [`observe`](#observe),
`observeChanges` provides only the difference between the old and new
result set, not the entire contents of the document that changed.
`callbacks` may have the following functions as properties:
<dl class="callbacks">
<dt><span class="name">added(id, fields)</span>
<span class="or">or</span></dt>
<dt><span class="name">addedBefore(id, fields, before)</span></dt>
<dd>
{{#markdown}}
A new document entered the result set. It has the `id` and `fields`
specified. `fields` contains all fields of the document excluding the
`_id` field. The new document is before the document identified by
`before`, or at the end if `before` is `null`.
{{/markdown}}
</dd>
{{#dtdd "changed(id, fields)"}}
The document identified by `id` has changed. `fields` contains the
changed fields with their new values. If a field was removed from the
document then it will be present in `fields` with a value of
`undefined`.
{{/dtdd}}
{{#dtdd "movedBefore(id, before)"}}
The document identified by `id` changed its position in the ordered result set,
and now appears before the document identified by `before`.
{{/dtdd}}
{{#dtdd "removed(id)"}}
The document identified by `id` was removed from the result set.
{{/dtdd}}
</dl>
`observeChanges` is significantly more efficient if you do not use
`addedBefore` or `movedBefore`.
Before `observeChanges` returns, `added` (or `addedBefore`) will be called
zero or more times to deliver the initial results of the query.
`observeChanges` returns a live query handle, which is an object with a `stop`
method. Call `stop` with no arguments to stop calling the callback functions
and tear down the query. **The query will run forever until you call this.**
If
`observeChanges` is called from a `Tracker.autorun` computation, it is automatically
stopped when the computation is rerun or stopped.
(If the cursor was created with the option `reactive` set to false, it will
only deliver the initial results and will not call any further callbacks;
it is not necessary to call `stop` on the handle.)
{{#note}}
Unlike `observe`, `observeChanges` does not provide absolute position
information (that is, `atIndex` positions rather than `before`
positions.) This is for efficiency.
{{/note}}
Example:
```js
// Keep track of how many administrators are online.
var count = 0;
var query = Users.find({admin: true, onlineNow: true});
var handle = query.observeChanges({
added: function (id, user) {
count++;
console.log(user.name + " brings the total to " + count + " admins.");
},
removed: function () {
count--;
console.log("Lost one. We're now down to " + count + " admins.");
}
});
// After five seconds, stop keeping the count.
setTimeout(function () {handle.stop();}, 5000);
```
{{> autoApiBox "Mongo.ObjectID"}}
`Mongo.ObjectID` follows the same API as the [Node MongoDB driver
`ObjectID`](http://mongodb.github.com/node-mongodb-native/api-bson-generated/objectid.html)
class. Note that you must use the `equals` method (or [`EJSON.equals`](#ejson_equals)) to
compare them; the `===` operator will not work. If you are writing generic code
that needs to deal with `_id` fields that may be either strings or `ObjectID`s, use
[`EJSON.equals`](#ejson_equals) instead of `===` to compare them.
{{#note}}
`ObjectID` values created by Meteor will not have meaningful answers to their `getTimestamp`
method, since Meteor currently constructs them fully randomly.
{{/note}}
{{> apiBoxTitle name="Mongo-Style Selectors" id="selectors"}}
The simplest selectors are just a string or
[`Mongo.ObjectID`](#mongo_object_id). These selectors match the
document with that value in its `_id` field.
A slightly more complex form of selector is an object containing a set of keys
that must match in a document:
```js
// Matches all documents where deleted is false
{deleted: false}
// Matches all documents where the name and cognomen are as given
{name: "Rhialto", cognomen: "the Marvelous"}
// Matches every document
{}
```
But they can also contain more complicated tests:
```js
// Matches documents where age is greater than 18
{age: {$gt: 18}}
// Also matches documents where tags is an array containing "popular"
{tags: "popular"}
// Matches documents where fruit is one of three possibilities
{fruit: {$in: ["peach", "plum", "pear"]}}
```
See the [complete
documentation](http://docs.mongodb.org/manual/reference/operator/).
{{> apiBoxTitle name="Mongo-Style Modifiers" id="modifiers"}}
A modifier is an object that describes how to update a document in
place by changing some of its fields. Some examples:
```js
// Set the 'admin' property on the document to true
{$set: {admin: true}}
// Add 2 to the 'votes' property, and add "Traz"
// to the end of the 'supporters' array
{$inc: {votes: 2}, $push: {supporters: "Traz"}}
```
But if a modifier doesn't contain any $-operators, then it is instead
interpreted as a literal document, and completely replaces whatever was
previously in the database. (Literal document modifiers are not currently
supported by [validated updates](#allow).)
```
// Find the document with id "123", and completely replace it.
Users.update({_id: "123"}, {name: "Alice", friends: ["Bob"]});
```
See the [full list of
modifiers](http://docs.mongodb.org/manual/reference/operator/update/).
{{> apiBoxTitle name="Sort Specifiers" id="sortspecifiers"}}
Sorts may be specified using your choice of several syntaxes:
```
// All of these do the same thing (sort in ascending order by
// key "a", breaking ties in descending order of key "b")
[["a", "asc"], ["b", "desc"]]
["a", ["b", "desc"]]
{a: 1, b: -1}
```
The last form will only work if your JavaScript implementation
preserves the order of keys in objects. Most do, most of the time, but
it's up to you to be sure.
For local collections you can pass a comparator function which receives two
document objects, and returns -1 if the first document comes first in order,
1 if the second document comes first, or 0 if neither document comes before
the other. This is a Minimongo extension to MongoDB.
{{> apiBoxTitle name="Field Specifiers" id="fieldspecifiers"}}
Queries can specify a particular set of fields to include or exclude from the
result object.
To exclude specific fields from the result objects, the field specifier is a
dictionary whose keys are field names and whose values are `0`. All unspecified
fields are included.
```js
Users.find({}, {fields: {password: 0, hash: 0}})
```
To include only specific fields in the result documents, use `1` as
the value. The `_id` field is still included in the result.
```js
Users.find({}, {fields: {firstname: 1, lastname: 1}})
```
With one exception, it is not possible to mix inclusion and exclusion styles:
the keys must either be all 1 or all 0. The exception is that you may specify
`_id: 0` in an inclusion specifier, which will leave `_id` out of the result
object as well. However, such field specifiers can not be used with
[`observeChanges`](#observe_changes), [`observe`](#observe), cursors returned
from a [publish function](#meteor_publish), or cursors used in
`{{dstache}}#each}}` in a template. They may be used with [`fetch`](#fetch),
[`findOne`](#findone), [`forEach`](#foreach), and [`map`](#map).
<a href="http://docs.mongodb.org/manual/reference/operator/projection/">Field
operators</a> such as `$` and `$elemMatch` are not available on the client side
yet.
A more advanced example:
```js
Users.insert({ alterEgos: [{ name: "Kira", alliance: "murderer" },
{ name: "L", alliance: "police" }],
name: "Yagami Light" });
Users.findOne({}, { fields: { 'alterEgos.name': 1, _id: 0 } });
// returns { alterEgos: [{ name: "Kira" }, { name: "L" }] }
```
See <a href="http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/#projection">
the MongoDB docs</a> for details of the nested field rules and array behavior.
{{/template}}

View File

@@ -1,168 +0,0 @@
{{#template name="apiConnections"}}
<h2 id="connections"><span>Server connections</span></h2>
These functions manage and inspect the network connection between the
Meteor client and server.
{{> autoApiBox "Meteor.status"}}
This method returns the status of the connection between the client and
the server. The return value is an object with the following fields:
<dl class="objdesc">
{{#dtdd name="connected" type="Boolean"}}
True if currently connected to the server. If false, changes and
method invocations will be queued up until the connection is
reestablished.
{{/dtdd}}
{{#dtdd name="status" type="String"}}
Describes the current reconnection status. The possible
values are `connected` (the connection is up and
running), `connecting` (disconnected and trying to open a
new connection), `failed` (permanently failed to connect; e.g., the client
and server support different versions of DDP), `waiting` (failed
to connect and waiting to try to reconnect) and `offline` (user has disconnected the connection).
{{/dtdd}}
{{#dtdd name="retryCount" type="Number"}}
The number of times the client has tried to reconnect since the
connection was lost. 0 when connected.
{{/dtdd}}
{{#dtdd name="retryTime" type="Number or undefined"}}
The estimated time of the next reconnection attempt. To turn this
into an interval until the next reconnection, use
`retryTime - (new Date()).getTime()`. This key will
be set only when `status` is `waiting`.
{{/dtdd}}
{{#dtdd name="reason" type="String or undefined"}}
If `status` is `failed`, a description of why the connection failed.
{{/dtdd}}
</dl>
Instead of using callbacks to notify you on changes, this is
a [reactive](#reactivity) data source. You can use it in a
[template](#livehtmltemplates) or [computation](#tracker_autorun)
to get realtime updates.
{{> autoApiBox "Meteor.reconnect"}}
{{> autoApiBox "Meteor.disconnect"}}
Call this method to disconnect from the server and stop all
live data updates. While the client is disconnected it will not receive
updates to collections, method calls will be queued until the
connection is reestablished, and hot code push will be disabled.
Call [Meteor.reconnect](#meteor_reconnect) to reestablish the connection
and resume data transfer.
This can be used to save battery on mobile devices when real time
updates are not required.
{{> autoApiBox "Meteor.onConnection"}}
`onConnection` returns an object with a single method `stop`. Calling
`stop` unregisters the callback, so that this callback will no longer
be called on new connections.
The callback is called with a single argument, the server-side
`connection` representing the connection from the client. This object
contains the following fields:
<dl class="objdesc">
{{#dtdd name="id" type="String"}}
A globally unique id for this connection.
{{/dtdd}}
{{#dtdd name="close" type="Function"}}
Close this DDP connection. The client is free to reconnect, but will
receive a different connection with a new `id` if it does.
{{/dtdd}}
{{#dtdd name="onClose" type="Function"}}
Register a callback to be called when the connection is closed. If the
connection is already closed, the callback will be called immediately.
{{/dtdd}}
{{#dtdd name="clientAddress" type="String"}}
The IP address of the client in dotted form (such as `"127.0.0.1"`).
If you're running your Meteor server behind a proxy (so that clients
are connecting to the proxy instead of to your server directly),
you'll need to set the `HTTP_FORWARDED_COUNT` environment variable
for the correct IP address to be reported by `clientAddress`.
Set `HTTP_FORWARDED_COUNT` to an integer representing the number of
proxies in front of your server. For example, you'd set it to `"1"`
when your server was behind one proxy.
{{/dtdd}}
{{#dtdd name="httpHeaders" type="Object"}}
When the connection came in over an HTTP transport (such as with
Meteor's default SockJS implementation), this field contains
whitelisted HTTP headers.
Cookies are deliberately excluded from the headers as they are a
security risk for this transport. For details and alternatives, see
the [SockJS
documentation](https://github.com/sockjs/sockjs-node#authorisation).
{{/dtdd}}
</dl>
{{#note}}
Currently when a client reconnects to the server (such as after
temporarily losing its Internet connection), it will get a new
connection each time. The `onConnection` callbacks will be called
again, and the new connection will have a new connection `id`.
In the future, when client reconnection is fully implemented,
reconnecting from the client will reconnect to the same connection on
the server: the `onConnection` callback won't be called for that
connection again, and the connection will still have the same
connection `id`.
{{/note}}
{{> autoApiBox "DDP.connect"}}
To call methods on another Meteor application or subscribe to its data
sets, call `DDP.connect` with the URL of the application.
`DDP.connect` returns an object which provides:
* `subscribe` -
Subscribe to a record set. See
[Meteor.subscribe](#meteor_subscribe).
* `call` -
Invoke a method. See [Meteor.call](#meteor_call).
* `apply` -
Invoke a method with an argument array. See
[Meteor.apply](#meteor_apply).
* `methods` -
Define client-only stubs for methods defined on the remote server. See
[Meteor.methods](#meteor_methods).
* `status` -
Get the current connection status. See
[Meteor.status](#meteor_status).
* `reconnect` -
See [Meteor.reconnect](#meteor_reconnect).
* `disconnect` -
See [Meteor.disconnect](#meteor_disconnect).
* `onReconnect` - Set this to a function to be called as the first step of
reconnecting. This function can call methods which will be executed before
any other outstanding methods. For example, this can be used to re-establish
the appropriate authentication context on the new connection.
By default, clients open a connection to the server from which they're loaded.
When you call `Meteor.subscribe`, `Meteor.status`, `Meteor.call`, and
`Meteor.apply`, you are using a connection back to that default
server.
{{/template}}

View File

@@ -1,53 +0,0 @@
{{#template name="apiCore"}}
<h2 id="core"><span>Meteor Core</span></h2>
{{> autoApiBox "Meteor.isClient"}}
{{> autoApiBox "Meteor.isServer"}}
{{#note}}
`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.
{{/note}}
{{> autoApiBox "Meteor.isCordova"}}
{{> autoApiBox "Meteor.isDevelopment"}}
{{> autoApiBox "Meteor.isProduction"}}
{{> autoApiBox "Meteor.startup"}}
On a server, the function will run as soon as the server process is
finished starting. On a client, the function will run as soon as the DOM
is ready. Code wrapped in `Meteor.startup` always runs after all app
files have loaded, so you should put code here if you want to access
shared variables from other files.
The `startup` callbacks are called in the same order as the calls to
`Meteor.startup` were made.
On a client, `startup` callbacks from packages will be called
first, followed by `<body>` templates from your `.html` files,
followed by your application code.
// On server startup, if the database is empty, create some initial data.
if (Meteor.isServer) {
Meteor.startup(function () {
if (Rooms.find().count() === 0) {
Rooms.insert({name: "Initial room"});
}
});
}
{{> autoApiBox "Meteor.wrapAsync"}}
{{> autoApiBox "Meteor.defer"}}
{{> autoApiBox "Meteor.absoluteUrl"}}
{{> autoApiBox "Meteor.settings"}}
{{> autoApiBox "Meteor.release"}}
{{/template}}

View File

@@ -1,90 +0,0 @@
{{#template name="apiEjson"}}
<h2 id="ejson"><span>EJSON</span></h2>
EJSON is an extension of JSON to support more types. It supports all JSON-safe
types, as well as:
- **Date** (JavaScript `Date`)
- **Binary** (JavaScript `Uint8Array` or the
result of [`EJSON.newBinary`](#ejson_new_binary))
- **User-defined types** (see [`EJSON.addType`](#ejson_add_type). For example,
[`Mongo.ObjectID`](#mongo_object_id) is implemented this way.)
All EJSON serializations are also valid JSON. For example an object with a date
and a binary buffer would be serialized in EJSON as:
{
"d": {"$date": 1358205756553},
"b": {"$binary": "c3VyZS4="}
}
Meteor supports all built-in EJSON data types in publishers, method arguments
and results, Mongo databases, and [`Session`](#session) variables.
{{> autoApiBox "EJSON.parse"}}
{{> autoApiBox "EJSON.stringify"}}
{{> autoApiBox "EJSON.fromJSONValue"}}
{{> autoApiBox "EJSON.toJSONValue"}}
{{> autoApiBox "EJSON.equals"}}
{{> autoApiBox "EJSON.clone"}}
{{> autoApiBox "EJSON.newBinary"}}
Buffers of binary data are represented by `Uint8Array` instances on JavaScript
platforms that support them. On implementations of JavaScript that do not
support `Uint8Array`, binary data buffers are represented by standard arrays
containing numbers ranging from 0 to 255, and the `$Uint8ArrayPolyfill` key
set to `true`.
{{> autoApiBox "EJSON.isBinary"}}
{{> autoApiBox "EJSON.addType"}}
When you add a type to EJSON, Meteor will be able to use that type in:
- publishing objects of your type if you pass them to publish handlers.
- allowing your type in the return values or arguments to
[methods](#methods_header).
- storing your type client-side in Minimongo.
- allowing your type in [`Session`](#session) variables.
Instances of your type must implement [`typeName`](#ejson_type_typeName) and
[`toJSONValue`](#ejson_type_toJSONValue) methods, and may implement
[`clone`](#ejson_type_clone) and [`equals`](#ejson_type_equals) methods if the
default implementations are not sufficient.
{{> autoApiBox "EJSON.CustomType#typeName"}}
{{> autoApiBox "EJSON.CustomType#toJSONValue"}}
For example, the `toJSONValue` method for
[`Mongo.ObjectID`](#mongo_object_id) could be:
function () {
return this.toHexString();
};
{{> autoApiBox "EJSON.CustomType#clone"}}
If your type does not have a `clone` method, `EJSON.clone` will use
[`toJSONValue`](#ejson_type_toJSONValue) and the factory instead.
{{> autoApiBox "EJSON.CustomType#equals"}}
The `equals` method should define an [equivalence
relation](http://en.wikipedia.org/wiki/Equivalence_relation). It should have
the following properties:
- *Reflexivity* - for any instance `a`: `a.equals(a)` must be true.
- *Symmetry* - for any two instances `a` and `b`: `a.equals(b)` if and only if `b.equals(a)`.
- *Transitivity* - for any three instances `a`, `b`, and `c`: `a.equals(b)` and `b.equals(c)` implies `a.equals(c)`.
If your type does not have an `equals` method, `EJSON.equals` will compare the
result of calling [`toJSONValue`](#ejson_type_toJSONValue) instead.
{{/template}}

View File

@@ -1,57 +0,0 @@
{{#template name="apiEmail"}}
<h2 id="email"><span>Email</span></h2>
The `email` package allows sending email from a Meteor app. To use it, add the
package to your project by running in your terminal:
```bash
meteor add email
```
The server reads from the `MAIL_URL` environment variable to determine how to
send mail. Currently, Meteor supports sending mail over SMTP; the `MAIL_URL`
environment variable should be of the form
`smtp://USERNAME:PASSWORD@HOST:PORT/`.
If `MAIL_URL` is not set, `Email.send` outputs the message to standard output
instead.
{{> autoApiBox "Email.send"}}
You must provide the `from` option and at least one of `to`, `cc`, and `bcc`;
all other options are optional.
`Email.send` only works on the server. Here is an example of how a
client could use a server method call to send an email. (In an actual
application, you'd need to be careful to limit the emails that a
client could send, to prevent your server from being used as a relay
by spammers.)
// In your server code: define a method that the client can call
Meteor.methods({
sendEmail: function (to, from, subject, text) {
check([to, from, subject, text], [String]);
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: text
});
}
});
// In your client code: asynchronously send an email
Meteor.call('sendEmail',
'alice@example.com',
'bob@example.com',
'Hello from Meteor!',
'This is a test of Email.send.');
{{/template}}

View File

@@ -1,107 +0,0 @@
{{#template name="apiHttp"}}
<h2 id="http"><span>HTTP</span></h2>
`HTTP` provides an HTTP request API on the client and server. To use
these functions, add the HTTP package to your project by running in your
terminal:
```bash
meteor add http
```
{{> autoApiBox "HTTP.call"}}
This function initiates an HTTP request to a remote server.
On the server, this function can be run either synchronously or
asynchronously. If the callback is omitted, it runs synchronously
and the results are returned once the request completes successfully.
If the request was not successful, an error is thrown.
This is
useful when making server-to-server HTTP API calls from within Meteor
methods, as the method can succeed or fail based on the results of the
synchronous HTTP call. In this case, consider using
[`this.unblock()`](#method_unblock) to allow other methods on the same
connection to run in
the mean time. On the client, this function must be used
asynchronously by passing a callback.
Both HTTP and HTTPS protocols are supported. The `url` argument must be
an absolute URL including protocol and host name on the server, but may be
relative to the current host on the client. The `query` option
replaces the query string of `url`. Parameters specified in `params`
that are put in the URL are appended to any query string.
For example, with a `url` of `"/path?query"` and
`params` of `{foo:"bar"}`, the final URL will be `"/path?query&foo=bar"`.
The `params` are put in the URL or the request body, depending on the
type of request. In the case of request with no bodies, like GET and
HEAD, the parameters will always go in the URL. For a POST or other
type of request, the parameters will be encoded into the body with a
standard `x-www-form-urlencoded` content type, unless the `content`
or `data` option is used to specify a body, in which case the
parameters will be appended to the URL instead.
When run in asynchronous mode, the callback receives two arguments,
`error` and `result`. The
`error` argument will contain an Error if the request fails in any
way, including a network error, time-out, or an HTTP status code in
the 400 or 500 range. In case of a 4xx/5xx HTTP status code, the
`response` property on `error` matches the contents of the result
object. When run in synchronous mode, either `result` is returned
from the function, or `error` is thrown.
Contents of the result object:
<dl class="objdesc">
<dt><span class="name">statusCode</span>
<span class="type">Number</span></dt>
<dd>Numeric HTTP result status code, or <code>null</code> on error.</dd>
<dt><span class="name">content</span>
<span class="type">String</span></dt>
<dd>The body of the HTTP response as a string.</dd>
<dt><span class="name">data</span>
<span class="type">Object or <code>null</code></span></dt>
<dd>If the response headers indicate JSON content, this contains the body of the document parsed as a JSON object.</dd>
<dt><span class="name">headers</span>
<span class="type">Object</span></dt>
<dd>A dictionary of HTTP headers from the response.</dd>
</dl>
Example server method:
Meteor.methods({checkTwitter: function (userId) {
check(userId, String);
this.unblock();
try {
var result = HTTP.call("GET", "http://api.twitter.com/xyz",
{params: {user: userId}});
return true;
} catch (e) {
// Got a network error, time-out or HTTP error in the 400 or 500 range.
return false;
}
}});
Example asynchronous HTTP call:
HTTP.call("POST", "http://api.twitter.com/xyz",
{data: {some: "json", stuff: 1}},
function (error, result) {
if (!error) {
Session.set("twizzled", true);
}
});
{{> autoApiBox "HTTP.get"}}
{{> autoApiBox "HTTP.post"}}
{{> autoApiBox "HTTP.put"}}
{{> autoApiBox "HTTP.del"}}
{{/template}}

View File

@@ -1,219 +0,0 @@
{{#template name="apiMethods"}}
<h2 id="methods_header"><span>Methods</span></h2>
Methods are remote functions that Meteor clients can invoke.
{{> autoApiBox "Meteor.methods"}}
Example:
```js
Meteor.methods({
foo: function (arg1, arg2) {
check(arg1, String);
check(arg2, [Number]);
// .. do stuff ..
if (/* you want to throw an error */) {
throw new Meteor.Error("pants-not-found", "Can't find my pants");
}
return "some return value";
},
bar: function () {
// .. do other stuff ..
return "baz";
}
});
```
Calling `methods` on the server defines functions that can be called remotely by
clients. They should return an [EJSON](#ejson)-able value or throw an
exception. Inside your method invocation, `this` is bound to a method
invocation object, which provides the following:
* `isSimulation`: a boolean value, true if this invocation is a stub.
* `unblock`: when called, allows the next method from this client to
begin running.
* `userId`: the id of the current user.
* `setUserId`: a function that associates the current client with a user.
* `connection`: on the server, the [connection](#meteor_onconnection) this method call was received on.
Calling `methods` on the client defines *stub* functions associated with
server methods of the same name. You don't have to define a stub for
your method if you don't want to. In that case, method calls are just
like remote procedure calls in other systems, and you'll have to wait
for the results from the server.
If you do define a stub, when a client invokes a server method it will
also run its stub in parallel. On the client, the return value of a
stub is ignored. Stubs are run for their side-effects: they are
intended to *simulate* the result of what the server's method will do,
but without waiting for the round trip delay. If a stub throws an
exception it will be logged to the console.
You use methods all the time, because the database mutators
([`insert`](#insert), [`update`](#update), [`remove`](#remove)) are implemented
as methods. When you call any of these functions on the client, you're invoking
their stub version that update the local cache, and sending the same write
request to the server. When the server responds, the client updates the local
cache with the writes that actually occurred on the server.
You don't have to put all your method definitions into a single `Meteor.methods`
call; you may call it multiple times, as long as each method has a unique name.
If a client calls a method and is disconnected before it receives a response,
it will re-call the method when it reconnects. This means that a client may
call a method multiple times when it only means to call it once. If this
behavior is problematic for your method, consider attaching a unique ID
to each method call on the client, and checking on the server whether a call
with this ID has already been made. Alternatively, you can use
[`Meteor.apply`](#meteor_apply) with the noRetry option set to true.
Read more about methods and how to use them in the [Methods](http://guide.meteor.com/methods.html) article in the Meteor Guide.
{{> autoApiBox "DDPCommon.MethodInvocation#userId"}}
The user id is an arbitrary string &mdash; typically the id of the user record
in the database. You can set it with the `setUserId` function. If you're using
the [Meteor accounts system](#accounts_api) then this is handled for you.
{{> autoApiBox "DDPCommon.MethodInvocation#setUserId"}}
Call this function to change the currently logged in user on the
connection that made this method call. This simply sets the value of
`userId` for future method calls received on this connection. Pass
`null` to log out the connection.
If you are using the [built-in Meteor accounts system](#accounts_api) then this
should correspond to the `_id` field of a document in the
[`Meteor.users`](#meteor_users) collection.
`setUserId` is not retroactive. It affects the current method call and
any future method calls on the connection. Any previous method calls on
this connection will still see the value of `userId` that was in effect
when they started.
{{> autoApiBox "DDPCommon.MethodInvocation#isSimulation"}}
{{> autoApiBox "DDPCommon.MethodInvocation#unblock"}}
On the server, methods from a given client run one at a time. The N+1th
invocation from a client won't start until the Nth invocation
returns. However, you can change this by calling `this.unblock`. This
will allow the N+1th invocation to start running in a new fiber.
{{> autoApiBox "DDPCommon.MethodInvocation#connection"}}
{{> autoApiBox "Meteor.Error"}}
If you want to return an error from a method, throw an exception. Methods can
throw any kind of exception. But `Meteor.Error` is the only kind of error that
a server will send to the client. If a method function throws a different
exception, then it will be mapped to a sanitized version on the
wire. Specifically, if the `sanitizedError` field on the thrown error is set to
a `Meteor.Error`, then that error will be sent to the client. Otherwise, if no
sanitized version is available, the client gets
`Meteor.Error(500, 'Internal server error')`.
{{> autoApiBox "Meteor.call"}}
This is how to invoke a method. It will run the method on the server. If a
stub is available, it will also run the stub on the client. (See also
[`Meteor.apply`](#meteor_apply), which is identical to `Meteor.call` except that
you specify the parameters as an array instead of as separate arguments and you
can specify a few options controlling how the method is executed.)
If you include a callback function as the last argument (which can't be
an argument to the method, since functions aren't serializable), the
method will run asynchronously: it will return nothing in particular and
will not throw an exception. When the method is complete (which may or
may not happen before `Meteor.call` returns), the callback will be
called with two arguments: `error` and `result`. If an error was thrown,
then `error` will be the exception object. Otherwise, `error` will be
undefined and the return value (possibly undefined) will be in `result`.
// async call
Meteor.call('foo', 1, 2, function (error, result) { ... } );
If you do not pass a callback on the server, the method invocation will
block until the method is complete. It will eventually return the
return value of the method, or it will throw an exception if the method
threw an exception. (Possibly mapped to 500 Server Error if the
exception happened remotely and it was not a `Meteor.Error` exception.)
// sync call
var result = Meteor.call('foo', 1, 2);
On the client, if you do not pass a callback and you are not inside a
stub, `call` will return `undefined`, and you will have no way to get
the return value of the method. That is because the client doesn't have
fibers, so there is not actually any way it can block on the remote
execution of a method.
Finally, if you are inside a stub on the client and call another
method, the other method is not executed (no RPC is generated, nothing
"real" happens). If that other method has a stub, that stub stands in
for the method and is executed. The method call's return value is the
return value of the stub function. The client has no problem executing
a stub synchronously, and that is why it's okay for the client to use
the synchronous `Meteor.call` form from inside a method body, as
described earlier.
Meteor tracks the database writes performed by methods, both on the client and
the server, and does not invoke `asyncCallback` until all of the server's writes
replace the stub's writes in the local cache. In some cases, there can be a lag
between the method's return value being available and the writes being visible:
for example, if another method still outstanding wrote to the same document, the
local cache may not be up to date until the other method finishes as well. If
you want to process the method's result as soon as it arrives from the server,
even if the method's writes are not available yet, you can specify an
`onResultReceived` callback to [`Meteor.apply`](#meteor_apply).
{{> autoApiBox "Meteor.apply"}}
`Meteor.apply` is just like `Meteor.call`, except that the method arguments are
passed as an array rather than directly as arguments, and you can specify
options about how the client executes the method.
<h2 id="ddpratelimiter"><span>DDPRateLimiter</span></h2>
Customize rate limiting for methods and subscriptions.
By default, `DDPRateLimiter` is configured with a single rule. This rule
limits login attempts, new user creation, and password resets to 5 attempts
every 10 seconds per connection. It can be removed by calling
`Accounts.removeDefaultRateLimit()`.
{{> autoApiBox "DDPRateLimiter.addRule"}}
Custom rules can be added by calling `DDPRateLimiter.addRule`. The rate
limiter is called on every method and subscription invocation.
A rate limit is reached when a bucket has surpassed the rule's predefined
capactiy, at which point errors will be returned for that input until the
buckets are reset. Buckets are regularly reset after the end of a time
interval.
Here's example of defining a rule and adding it into the `DDPRateLimiter`:
```javascript
// Define a rule that matches login attempts by non-admin users
var loginRule = {
userId: function (userId) {
return Meteor.users.findOne(userId).type !== 'Admin';
},
type: 'method',
name: 'login'
}
// Add the rule, allowing up to 5 messages every 1000 milliseconds.
DDPRateLimiter.addRule(loginRule, 5, 1000);
```
{{> autoApiBox "DDPRateLimiter.removeRule"}}
{{> autoApiBox "DDPRateLimiter.setErrorMessage"}}
{{/template}}
{{> auto}}

View File

@@ -1,60 +0,0 @@
{{#template name="apiMobileConfig"}}
<h2 id="mobileconfigjs"><span>Mobile Config File</span></h2>
If your Meteor application targets mobile platforms such as iOS or
Android, you can configure your app's metadata and build process
in a special top-level file called
`mobile-config.js` which is *not* included in your application and is used only
for this configuration.
The code snippet below is an example `mobile-config.js` file. The rest of this
section will explain the specific API commands in greater detail.
```javascript
// This section sets up some basic app metadata,
// the entire section is optional.
App.info({
id: 'com.example.matt.uber',
name: 'über',
description: 'Get über power in one button click',
author: 'Matt Development Group',
email: 'contact@example.com',
website: 'http://example.com'
});
// Set up resources such as icons and launch screens.
App.icons({
'iphone': 'icons/icon-60.png',
'iphone_2x': 'icons/icon-60@2x.png',
// ... more screen sizes and platforms ...
});
App.launchScreens({
'iphone': 'splash/Default~iphone.png',
'iphone_2x': 'splash/Default@2x~iphone.png',
// ... more screen sizes and platforms ...
});
// Set PhoneGap/Cordova preferences
App.setPreference('BackgroundColor', '0xff0000ff');
App.setPreference('HideKeyboardFormAccessoryBar', true);
App.setPreference('Orientation', 'default');
App.setPreference('Orientation', 'all', 'ios');
// Pass preferences for a particular PhoneGap/Cordova plugin
App.configurePlugin('com.phonegap.plugins.facebookconnect', {
APP_ID: '1234567890',
API_KEY: 'supersecretapikey'
});
```
{{> autoApiBox "App.info"}}
{{> autoApiBox "App.setPreference"}}
{{> autoApiBox "App.accessRule"}}
{{> autoApiBox "App.configurePlugin"}}
{{> autoApiBox "App.icons"}}
{{> autoApiBox "App.launchScreens"}}
{{/template}}

View File

@@ -1,132 +0,0 @@
{{#template name="apiPackagejs"}}
<h2 id="packagejs"><span>Package.js</span></h2>
{{#markdown}} A package is a directory containing a package.js file, which
contains roughly three major sections: a basic description, a package
definition, and a test definition. By default, the directory name is the name of
the package.
The `package.js` file below is an example of how to use the packaging API. The
rest of this section will explain the specific API commands in greater detail.
/* Information about this package */
Package.describe({
// Short two-sentence summary.
summary: "What this does",
// Version number.
version: "1.0.0",
// Optional. Default is package directory name.
name: "username:package-name",
// Optional github URL to your source repository.
git: "https://github.com/something/something.git",
});
/* This defines your actual package */
Package.onUse(function (api) {
// If no version is specified for an 'api.use' dependency, use the
// one defined in Meteor 0.9.0.
api.versionsFrom('0.9.0');
// Use Underscore package, but only on the server.
// Version not specified, so it will be as of Meteor 0.9.0.
api.use('underscore', 'server');
// Use iron:router package, version 1.0.0 or newer.
api.use('iron:router@1.0.0');
// Give users of this package access to the Templating package.
api.imply('templating')
// Export the object 'Email' to packages or apps that use this package.
api.export('Email', 'server');
// Specify the source code for the package.
api.addFiles('email.js', 'server');
});
/* This defines the tests for the package */
Package.onTest(function (api) {
// Sets up a dependency on this package
api.use('username:package-name');
// Allows you to use the 'tinytest' framework
api.use('tinytest@1.0.0');
// Specify the source code for the package tests
api.addFiles('email_tests.js', 'server');
});
/* This lets you use npm packages in your package*/
Npm.depends({
simplesmtp: "0.3.10",
"stream-buffers": "0.2.5"});
Build plugins are created with
[`Package.registerBuildPlugin`](#Package-registerBuildPlugin). See the
coffeescript package for an example. Build plugins are fully-fledged Meteor
programs in their own right and have their own namespace, package dependencies,
source files and npm requirements.
{{#note}}
You can use [local packages](#writingpackages) to define custom build plugins
for your app, with one caveat. In published packages, build plugins are already
bundled with their transitive dependencies. So if you want a dependency of a
build plugin to be satisfied by a local package, you must use a local copy of
the package that defines the plugin (even if you make no changes to that
package) so that Meteor will pick up the local dependency.
{{/note}}
<h3 id="packagedescription"><span>Package Description</span></h3>
Provide basic package information with `Package.describe(options)`. To publish a
package, you must define `summary` and `version`.
{{/markdown}}
{{> autoApiBox "Package.describe"}}
<h3 id="packagedefinition"><span>Package Definition</span></h3>
{{#markdown}}
Define dependencies and expose package methods with the
`Package.onUse` handler. This section lets you define what packages your package
depends on, what packages are implied by your package, and what object your
package is exported to.
{{/markdown}}
{{> autoApiBox "Package.onUse"}}
{{> autoApiBox "PackageAPI#versionsFrom" }}
{{> autoApiBox "PackageAPI#use" }}
{{> autoApiBox "PackageAPI#imply" }}
{{> autoApiBox "PackageAPI#export" }}
{{> autoApiBox "PackageAPI#addFiles" }}
{{> autoApiBox "PackageAPI#addAssets" }}
<h3 id="packagetests"><span>Unit Tests</span></h3>
{{#markdown}}
Set up your tests with the `Package.onTest` handler, which has an interface
that's parallel to that of the `onUse` handler. The tests will need to depend on
the package that you have just created. For example, if your package is the
`email` package, you have to call `api.use('email')` in order to test the
package.
If you used `meteor create` to set up your package, Meteor will create the
required scaffolding in `package.js`, and you'll only need to add unit test code
in the `_test.js` file that was created.
{{/markdown}}
{{> autoApiBox "Package.onTest"}}
<h3><span>External Packages and Plugins</span></h3>
{{#markdown}}
Meteor packages can include NPM packages and Cordova plugins by using
`Npm.depends` and `Cordova.depends` in the `package.js` file.
{{/markdown}}
{{> autoApiBox "Npm.depends"}}
{{> autoApiBox "Npm.require"}}
{{> autoApiBox "Cordova.depends"}}
{{> autoApiBox "Package.registerBuildPlugin"}}
{{> autoApiBox "Plugin.registerSourceHandler"}}
{{/template}}

View File

@@ -1,188 +0,0 @@
{{#template name="apiPasswords"}}
<h2 id="accounts_passwords"><span>Passwords</span></h2>
The `accounts-password` package contains a full system for password-based
authentication. In addition to the basic username and password-based
sign-in process, it also supports email-based sign-in including
address verification and password recovery emails.
The Meteor server stores passwords using the
[bcrypt](http://en.wikipedia.org/wiki/Bcrypt) algorithm. This helps
protect against embarrassing password leaks if the server's database is
compromised.
To add password support to your application, run this command in your terminal:
```bash
meteor add accounts-password
```
You can construct your own user interface using the
functions below, or use the [`accounts-ui` package](#accountsui) to
include a turn-key user interface for password-based sign-in.
{{> autoApiBox "Accounts.createUser"}}
On the client, this function logs in as the newly created user on
successful completion. On the server, it returns the newly created user
id.
On the client, you must pass `password` and at least one of `username` or
`email` &mdash; enough information for the user to be able to log in again
later. If there are existing users with a username or email only differing in
case, `createUser` will fail. On the server, you do not need to specify
`password`, but the user will not be able to log in until it has a password (eg,
set with [`Accounts.setPassword`](#accounts_setpassword)).
To create an account without a password on the server and still let the
user pick their own password, call `createUser` with the `email` option
and then
call [`Accounts.sendEnrollmentEmail`](#accounts_sendenrollmentemail). This
will send the user an email with a link to set their initial password.
By default the `profile` option is added directly to the new user document. To
override this behavior, use [`Accounts.onCreateUser`](#accounts_oncreateuser).
This function is only used for creating users with passwords. The external
service login flows do not use this function.
### Managing usernames and emails
Instead of modifying documents in the [`Meteor.users`](#meteor_users) collection
directly, use these convenience functions which correctly check for case
insensitive duplicates before updates.
{{> autoApiBox "Accounts.setUsername"}}
{{> autoApiBox "Accounts.addEmail"}}
By default, an email address is added with `{ verified: false }`. Use
[`Accounts.sendVerificationEmail`](#Accounts-sendVerificationEmail) to send an
email with a link the user can use verify their email address.
{{> autoApiBox "Accounts.removeEmail"}}
{{> autoApiBox "Accounts.verifyEmail"}}
This function accepts tokens passed into the callback registered with
[`Accounts.onEmailVerificationLink`](#Accounts-onEmailVerificationLink).
{{> autoApiBox "Accounts.findUserByUsername"}}
{{> autoApiBox "Accounts.findUserByEmail"}}
### Managing passwords
Use the below functions to initiate password changes or resets from the server
or the client.
{{> autoApiBox "Accounts.changePassword"}}
{{> autoApiBox "Accounts.forgotPassword"}}
This triggers a call
to [`Accounts.sendResetPasswordEmail`](#accounts_sendresetpasswordemail)
on the server. When the user visits the link in this email, the callback
registered with [`Accounts.onResetPasswordLink`](#Accounts-onResetPasswordLink)
will be called.
If you are using the [`accounts-ui` package](#accountsui), this is handled
automatically. Otherwise, it is your responsibility to prompt the user for the
new password and call `resetPassword`.
{{> autoApiBox "Accounts.resetPassword"}}
This function accepts tokens passed into the callbacks registered with
[`AccountsClient#onResetPasswordLink`](#Accounts-onResetPasswordLink) and
[`Accounts.onEnrollmentLink`](#Accounts-onEnrollmentLink).
{{> autoApiBox "Accounts.setPassword"}}
<h3 id="sending-emails"><span>Sending emails</span></h3>
{{> autoApiBox "Accounts.sendResetPasswordEmail"}}
When the user visits the link in this email, the callback registered with
[`AccountsClient#onResetPasswordLink`](#Accounts-onResetPasswordLink) will be called.
To customize the contents of the email, see
[`Accounts.emailTemplates`](#accounts_emailtemplates).
{{> autoApiBox "Accounts.sendEnrollmentEmail"}}
When the user visits the link in this email, the callback registered with
[`Accounts.onEnrollmentLink`](#Accounts-onEnrollmentLink) will be called.
To customize the contents of the email, see
[`Accounts.emailTemplates`](#accounts_emailtemplates).
{{> autoApiBox "Accounts.sendVerificationEmail"}}
When the user visits the link in this email, the callback registered with
[`Accounts.onEmailVerificationLink`](#Accounts-onEmailVerificationLink) will
be called.
To customize the contents of the email, see
[`Accounts.emailTemplates`](#accounts_emailtemplates).
{{> autoApiBox "Accounts.onResetPasswordLink"}}
{{> autoApiBox "Accounts.onEnrollmentLink"}}
{{> autoApiBox "Accounts.onEmailVerificationLink"}}
{{> autoApiBox "Accounts.emailTemplates"}}
This is an `Object` with several fields that are used to generate text/html
for the emails sent by `sendResetPasswordEmail`, `sendEnrollmentEmail`,
and `sendVerificationEmail`.
Override fields of the object by assigning to them:
- `from`: A `String` with an [RFC5322](http://tools.ietf.org/html/rfc5322) From
address. By default, the email is sent from `no-reply@meteor.com`. If you
wish to receive email from users asking for help with their account, be sure
to set this to an email address that you can receive email at.
- `siteName`: The public name of your application. Defaults to the DNS name of
the application (eg: `awesome.meteor.com`).
- `headers`: An `Object` for custom email headers as described in
[`Email.send`](#email_send).
- `resetPassword`: An `Object` with the fields:
- `from`: A `Function` used to override the `from` address defined
by the `emailTemplates.from` field.
- `subject`: A `Function` that takes a user object and returns
a `String` for the subject line of a reset password email.
- `text`: An optional `Function` that takes a user object and a url, and
returns the body text for a reset password email.
- `html`: An optional `Function` that takes a user object and a
url, and returns the body html for a reset password email.
- `enrollAccount`: Same as `resetPassword`, but for initial password setup for
new accounts.
- `verifyEmail`: Same as `resetPassword`, but for verifying the users email
address.
Example:
```js
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.enrollAccount.subject = function (user) {
return "Welcome to Awesome Town, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.text = function (user, url) {
return "You have been selected to participate in building a better future!"
+ " To activate your account, simply click the link below:\n\n"
+ url;
};
```
{{/template}}

View File

@@ -1,227 +0,0 @@
{{#template name="apiPubsub"}}
<h2 id="publishandsubscribe"><span>Publish and subscribe</span></h2>
These functions control how Meteor servers publish sets of records and
how clients can subscribe to those sets.
{{> autoApiBox "Meteor.publish"}}
To publish records to clients, call `Meteor.publish` on the server with
two parameters: the name of the record set, and a *publish function*
that Meteor will call each time a client subscribes to the name.
Publish functions can return a
[`Collection.Cursor`](#mongo_cursor), in which case Meteor
will publish that cursor's documents to each subscribed client. You can
also return an array of `Collection.Cursor`s, in which case Meteor will
publish all of the cursors.
{{#warning}}
If you return multiple cursors in an array, they currently must all be from
different collections. We hope to lift this restriction in a future release.
{{/warning}}
// server: publish the rooms collection, minus secret info.
Meteor.publish("rooms", function () {
return Rooms.find({}, {fields: {secretInfo: 0}});
});
// ... and publish secret info for rooms where the logged-in user
// is an admin. If the client subscribes to both streams, the records
// are merged together into the same documents in the Rooms collection.
Meteor.publish("adminSecretInfo", function () {
return Rooms.find({admin: this.userId}, {fields: {secretInfo: 1}});
});
// publish dependent documents and simulate joins
Meteor.publish("roomAndMessages", function (roomId) {
check(roomId, String);
return [
Rooms.find({_id: roomId}, {fields: {secretInfo: 0}}),
Messages.find({roomId: roomId})
];
});
Alternatively, a publish function can directly control its published record set
by calling the functions [`added`](#publish_added) (to add a new document to the
published record set), [`changed`](#publish_changed) (to change or clear some
fields on a document already in the published record set), and
[`removed`](#publish_removed) (to remove documents from the published record
set). These methods are provided by `this` in your publish function.
If a publish function does not return a cursor or array of cursors, it is
assumed to be using the low-level `added`/`changed`/`removed` interface, and it
**must also call [`ready`](#publish_ready) once the initial record set is
complete**.
Example:
// server: publish the current size of a collection
Meteor.publish("counts-by-room", function (roomId) {
var self = this;
check(roomId, String);
var count = 0;
var initializing = true;
// observeChanges only returns after the initial `added` callbacks
// have run. Until then, we don't want to send a lot of
// `self.changed()` messages - hence tracking the
// `initializing` state.
var handle = Messages.find({roomId: roomId}).observeChanges({
added: function (id) {
count++;
if (!initializing)
self.changed("counts", roomId, {count: count});
},
removed: function (id) {
count--;
self.changed("counts", roomId, {count: count});
}
// don't care about changed
});
// Instead, we'll send one `self.added()` message right after
// observeChanges has returned, and mark the subscription as
// ready.
initializing = false;
self.added("counts", roomId, {count: count});
self.ready();
// Stop observing the cursor when client unsubs.
// Stopping a subscription automatically takes
// care of sending the client any removed messages.
self.onStop(function () {
handle.stop();
});
});
// client: declare collection to hold count object
Counts = new Mongo.Collection("counts");
// client: subscribe to the count for the current room
Tracker.autorun(function () {
Meteor.subscribe("counts-by-room", Session.get("roomId"));
});
// client: use the new collection
console.log("Current room has " +
Counts.findOne(Session.get("roomId")).count +
" messages.");
// server: sometimes publish a query, sometimes publish nothing
Meteor.publish("secretData", function () {
if (this.userId === 'superuser') {
return SecretData.find();
} else {
// Declare that no data is being published. If you leave this line
// out, Meteor will never consider the subscription ready because
// it thinks you're using the added/changed/removed interface where
// you have to explicitly call this.ready().
return [];
}
});
{{#warning}}
Meteor will emit a warning message if you call `Meteor.publish` in a
project that includes the `autopublish` package. Your publish function
will still work.
{{/warning}}
Read more about publications and how to use them in the [Data Loading](http://guide.meteor.com/data-loading.html) article in the Meteor Guide.
{{> autoApiBox "Subscription#userId"}}
This is constant. However, if the logged-in user changes, the publish
function is rerun with the new value.
{{> autoApiBox "Subscription#added"}}
{{> autoApiBox "Subscription#changed"}}
{{> autoApiBox "Subscription#removed"}}
{{> autoApiBox "Subscription#ready"}}
{{> autoApiBox "Subscription#onStop"}}
If you call [`observe`](#observe) or [`observeChanges`](#observe_changes) in your
publish handler, this is the place to stop the observes.
{{> autoApiBox "Subscription#error"}}
{{> autoApiBox "Subscription#stop"}}
{{> autoApiBox "Subscription#connection"}}
{{> autoApiBox "Meteor.subscribe"}}
When you subscribe to a record set, it tells the server to send records to the
client. The client stores these records in local [Minimongo
collections](#mongo_collection), with the same name as the `collection`
argument used in the publish handler's [`added`](#publish_added),
[`changed`](#publish_changed), and [`removed`](#publish_removed)
callbacks. Meteor will queue incoming records until you declare the
[`Mongo.Collection`](#mongo_collection) on the client with the matching
collection name.
// okay to subscribe (and possibly receive data) before declaring
// the client collection that will hold it. assume "allplayers"
// publishes data from server's "players" collection.
Meteor.subscribe("allplayers");
...
// client queues incoming players records until ...
...
Players = new Mongo.Collection("players");
The client will see a document if the document is currently in the published
record set of any of its subscriptions.
The `onReady` callback is called with no arguments when the server [marks the
subscription as ready](#publish_ready). The `onStop` callback is called with
a [`Meteor.Error`](#meteor_error) if the subscription fails or is terminated by
the server. If the subscription is stopped by calling `stop` on the subscription
handle or inside the publication, `onStop` is called with no arguments.
`Meteor.subscribe` returns a subscription handle, which is an object with the
following properties:
<dl class="callbacks">
{{#dtdd "stop()"}}
Cancel the subscription. This will typically result in the server directing the
client to remove the subscription's data from the client's cache.
{{/dtdd}}
{{#dtdd "ready()"}}
True if the server has [marked the subscription as ready](#publish_ready). A
reactive data source.
{{/dtdd}}
{{#dtdd "subscriptionId"}}
The `id` of the subscription this handle is for. When you run `Meteor.subscribe`
inside of `Tracker.autorun`, the handles you get will always have the same
`subscriptionId` field. You can use this to deduplicate subscription handles
if you are storing them in some data structure.
{{/dtdd}}
</dl>
If you call `Meteor.subscribe` within a [reactive computation](#reactivity),
for example using
[`Tracker.autorun`](#tracker_autorun), the subscription will automatically be
cancelled when the computation is invalidated or stopped; it's not necessary
to call `stop` on
subscriptions made from inside `autorun`. However, if the next iteration
of your run function subscribes to the same record set (same name and
parameters), Meteor is smart enough to skip a wasteful
unsubscribe/resubscribe. For example:
Tracker.autorun(function () {
Meteor.subscribe("chat", {room: Session.get("current-room")});
Meteor.subscribe("privateMessages");
});
This subscribes you to the chat messages in the current room and to your private
messages. When you change rooms by calling `Session.set("current-room",
"new-room")`, Meteor will subscribe to the new room's chat messages,
unsubscribe from the original room's chat messages, and continue to
stay subscribed to your private messages.
If more than one subscription sends conflicting values for a field (same
collection name, document ID, and field name), then the value on the client will
be one of the published values, chosen arbitrarily.
{{/template}}

View File

@@ -1,45 +0,0 @@
{{#template name="apiReactiveVar"}}
<h2 id="reactivevar_pkg"><span>ReactiveVar</span></h2>
To use `ReactiveVar`, add the `reactive-var` package to your project by running
in your terminal:
```bash
meteor add reactive-var
```
{{> autoApiBox "ReactiveVar"}}
A ReactiveVar holds a single value that can be get and set, such that calling
`set` will invalidate any Computations that called `get`, according to the
usual contract for reactive data sources.
A ReactiveVar is similar to a Session variable, with a few differences:
* ReactiveVars don't have global names, like the "foo" in `Session.get("foo")`.
Instead, they may be created and used locally, for example attached to a
template instance, as in: `this.foo.get()`.
* ReactiveVars are not automatically migrated across hot code pushes,
whereas Session state is.
* ReactiveVars can hold any value, while Session variables are limited to
JSON or EJSON.
An important property of ReactiveVars &mdash; which is sometimes a
reason for using one &mdash; is that setting the value to the same
value as before has no effect; it does not trigger any invalidations.
So if one autorun sets a ReactiveVar, and another autorun gets the
ReactiveVar, a re-run of the first autorun won't necessarily trigger
the second. By default, only primitive values are compared this way,
while calling `set` on an argument that is an *object* (not a
primitive) always counts as a change. You can configure this behavior
using the `equalsFunc` argument.
{{> autoApiBox "ReactiveVar#get"}}
{{> autoApiBox "ReactiveVar#set"}}
{{/template}}

View File

@@ -1,132 +0,0 @@
{{#template name="apiSession"}}
<h2 id="session"><span>Session</span></h2>
`Session` provides a global object on the client that you can use to
store an arbitrary set of key-value pairs. Use it to store things like
the currently selected item in a list.
What's special about `Session` is that it's reactive. If
you call [`Session.get`](#session_get)`("currentList")`
from inside a template, the template will automatically be rerendered
whenever [`Session.set`](#session_set)`("currentList", x)` is called.
{{> autoApiBox "Session.set"}}
Example:
```js
Tracker.autorun(function () {
Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")});
});
// Causes the function passed to Tracker.autorun to be re-run, so
// that the chat-history subscription is moved to the room "home".
Session.set("currentRoomId", "home");
```
`Session.set` can also be called with an object of keys and values, which is
equivalent to calling `Session.set` individually on each key/value pair.
```js
Session.set({
a: "foo",
b: "bar"
});
```
{{> autoApiBox "Session.setDefault"}}
This is useful in initialization code, to avoid re-initializing a session
variable every time a new version of your app is loaded.
{{> autoApiBox "Session.get"}}
Example:
```html
<!-- in main.html -->
<template name="main">
<p>We've always been at war with {{dstache}}theEnemy}}.</p>
{{lt}}/template>
```
```js
// in main.js
Template.main.helpers({
theEnemy: function () {
return Session.get("enemy");
}
});
Session.set("enemy", "Eastasia");
// Page will say "We've always been at war with Eastasia"
Session.set("enemy", "Eurasia");
// Page will change to say "We've always been at war with Eurasia"
```
{{> autoApiBox "Session.equals"}}
If value is a scalar, then these two expressions do the same thing:
(1) Session.get("key") === value
(2) Session.equals("key", value)
... but the second one is always better. It triggers fewer invalidations
(template redraws), making your program more efficient.
Example:
```html
{{lt}}template name="postsView">
{{dstache}}! Show a dynamically updating list of items. Let the user click on an
item to select it. The selected item is given a CSS class so it
can be rendered differently. }}
{{dstache}}#each posts}}
{{dstache}}> postItem }}
{{dstache}}/each}}
{{lt}}/template>
{{lt}}template name="postItem">
<div class="{{dstache}}postClass}}">{{dstache}}title}}</div>
{{lt}}/template>
```
```js
// in JS file
Template.postsView.helpers({
posts: function() {
return Posts.find();
}
});
Template.postItem.helpers({
postClass: function() {
return Session.equals("selectedPost", this._id) ?
"selected" : "";
}
});
Template.postItem.events({
'click': function() {
Session.set("selectedPost", this._id);
}
});
```
Using Session.equals here means that when the user clicks
on an item and changes the selection, only the newly selected
and the newly unselected items are re-rendered.
If Session.get had been used instead of Session.equals, then
when the selection changed, all the items would be re-rendered.
For object and array session values, you cannot use `Session.equals`; instead,
you need to use the `underscore` package and write
`_.isEqual(Session.get(key), value)`.
{{/template}}

View File

@@ -1,511 +0,0 @@
{{#template name="apiTemplates"}}
<h2 id="templates_api"><span>Templates</span></h2>
When you write a template as `<{{! }}template name="foo"> ... <{{!
}}/template>` in an HTML file in your app, Meteor generates a
"template object" named `Template.foo`. Note that template name cannot
contain hyphens and other special characters.
The same template may occur many times on a page, and these
occurrences are called template instances. Template instances have a
life cycle of being created, put into the document, and later taken
out of the document and destroyed. Meteor manages these stages for
you, including determining when a template instance has been removed
or replaced and should be cleaned up. You can associate data with a
template instance, and you can access its DOM nodes when it is in the
document.
Read more about templates and how to use them in the [Spacebars](#pkg_spacebars)
package README and the [Blaze](http://guide.meteor.com/blaze.html) article in the Meteor Guide.
{{> autoApiBox "Template#events"}}
Declare event handlers for instances of this template. Multiple calls add
new event handlers in addition to the existing ones.
See [Event Maps](#eventmaps) for a detailed description of the event
map format and how event handling works in Meteor.
{{> autoApiBox "Template#helpers"}}
Each template has a local dictionary of helpers that are made available to it,
and this call specifies helpers to add to the template's dictionary.
Example:
Template.myTemplate.helpers({
foo() {
return Session.get("foo");
}
});
Now you can invoke this helper with `{{dstache}}foo}}` in the template defined
with `<{{! }}template name="myTemplate">`.
Helpers can accept positional and keyword arguments:
```javascript
Template.myTemplate.helpers({
displayName(firstName, lastName, keyword) {
var prefix = keyword.hash.title ? keyword.hash.title + " " : "";
return prefix + firstName + " " + lastName;
}
});
```
Then you can call this helper from template like this:
```
{{dstache}}displayName "John" "Doe" title="President"}}
```
You can learn more about arguments to helpers in [Spacebars
Readme](https://atmospherejs.com/meteor/spacebars).
Under the hood, each helper starts a new
[`Tracker.autorun`](#/full/tracker_autorun). When its reactive
dependencies change, the helper is rerun. Helpers depend on their data
context, passed arguments and other reactive data sources accessed during
execution.
To create a helper that can be used in any template, use
[`Template.registerHelper`](#template_registerhelper).
{{> autoApiBox "Template#onRendered"}}
Callbacks added with this method are called once when an instance of
Template.*myTemplate* is rendered into DOM nodes and put into the document for
the first time.
In the body of a callback, `this` is a [template instance](#template_inst)
object that is unique to this occurrence of the template and persists across
re-renderings. Use the `onCreated` and `onDestroyed` callbacks to perform
initialization or clean-up on the object.
Because your template has been rendered, you can use functions like
[`this.findAll`](#template_findAll) which look at its DOM nodes.
This can be a good place to apply any DOM manipulations you want, after the
template is rendered for the first time.
```html
<template name="myPictures">
<div class="container">
{{dstache}}#each pictures}}
<img class="item" src="/{{dstache}}.}}"/>
{{dstache}}/each}}
</div>
</template>
```
```javascript
Template.myPictures.onRendered(function () {
// Use the Packery jQuery plugin
this.$('.container').packery({
itemSelector: '.item',
gutter: 10
});
});
```
{{> autoApiBox "Template#onCreated"}}
Callbacks added with this method are called before your template's logic is
evaluated for the first time. Inside a callback, `this` is the new [template
instance](#template_inst) object. Properties you set on this object will be
visible from the callbacks added with `onRendered` and `onDestroyed` methods and
from event handlers.
These callbacks fire once and are the first group of callbacks to fire.
Handling the `created` event is a useful way to set up values on template
instance that are read from template helpers using `Template.instance()`.
```javascript
Template.myPictures.onCreated(function () {
// set up local reactive variables
this.highlightedPicture = new ReactiveVar(null);
// register this template within some central store
GalleryTemplates.push(this);
});
```
{{> autoApiBox "Template#onDestroyed"}}
These callbacks are called when an occurrence of a template is taken off
the page for any reason and not replaced with a re-rendering. Inside
a callback, `this` is the [template instance](#template_inst) object
being destroyed.
This group of callbacks is most useful for cleaning up or undoing any external
effects of `created` or `rendered` groups. This group fires once and is the last
callback to fire.
```javascript
Template.myPictures.onDestroyed(function () {
// deregister from some central store
GalleryTemplates = _.without(GalleryTemplates, this);
});
```
<h2 id="template_inst"><span>Template instances</span></h2>
A template instance object represents an occurrence of a template in
the document. It can be used to access the DOM and it can be
assigned properties that persist as the template is reactively updated.
Template instance objects are found as the value of `this` in the
`onCreated`, `onRendered`, and `onDestroyed` template callbacks, and as an
argument to event handlers. You can access the current template instance
from helpers using [`Template.instance()`](#template_instance).
In addition to the properties and functions described below, you can assign
additional properties of your choice to the object. Use the
[`onCreated`](#template_onCreated) and [`onDestroyed`](#template_onDestroyed)
methods to add callbacks performing initialization or clean-up on the object.
You can only access `findAll`, `find`, `firstNode`, and `lastNode` from the
`onRendered` callback and event handlers, not from `onCreated` and
`onDestroyed`, because they require the template instance to be in the DOM.
Template instance objects are `instanceof Blaze.TemplateInstance`.
{{> autoApiBox "Blaze.TemplateInstance#findAll"}}
`template.findAll` returns an array of DOM elements matching `selector`.
{{> autoApiBox "Blaze.TemplateInstance#$"}}
`template.$` returns a [jQuery object](http://api.jquery.com/Types/#jQuery) of
those same elements. jQuery objects are similar to arrays, with
additional methods defined by the jQuery library.
The template instance serves as the document root for the selector. Only
elements inside the template and its sub-templates can match parts of
the selector.
{{> autoApiBox "Blaze.TemplateInstance#find"}}
Returns one DOM element matching `selector`, or `null` if there are no
such elements.
The template instance serves as the document root for the selector. Only
elements inside the template and its sub-templates can match parts of
the selector.
{{> autoApiBox "Blaze.TemplateInstance#firstNode"}}
The two nodes `firstNode` and `lastNode` indicate the extent of the
rendered template in the DOM. The rendered template includes these
nodes, their intervening siblings, and their descendents. These two
nodes are siblings (they have the same parent), and `lastNode` comes
after `firstNode`, or else they are the same node.
{{> autoApiBox "Blaze.TemplateInstance#lastNode"}}
{{> autoApiBox "Blaze.TemplateInstance#data"}}
This property provides access to the data context at the top level of
the template. It is updated each time the template is re-rendered.
Access is read-only and non-reactive.
{{> autoApiBox "Blaze.TemplateInstance#autorun"}}
You can use `this.autorun` from an [`onCreated`](#template_onCreated) or
[`onRendered`](#template_onRendered) callback to reactively update the DOM
or the template instance. You can use `Template.currentData()` inside
of this callback to access reactive data context of the template instance.
The Computation is automatically stopped when the template is destroyed.
Alias for `template.view.autorun`.
{{> autoApiBox "Blaze.TemplateInstance#subscribe"}}
You can use `this.subscribe` from an [`onCreated`](#template_onCreated) callback
to specify which data publications this template depends on. The subscription is
automatically stopped when the template is destroyed.
There is a complementary function `Template.instance().subscriptionsReady()`
which returns true when all of the subscriptions called with `this.subscribe`
are ready.
Inside the template's HTML, you can use the built-in helper
`Template.subscriptionsReady`, which is an easy pattern for showing loading
indicators in your templates when they depend on data loaded from subscriptions.
Example:
```js
Template.notifications.onCreated(function () {
// Use this.subscribe inside onCreated callback
this.subscribe("notifications");
});
```
```html
<template name="notifications">
{{dstache}}#if Template.subscriptionsReady}}
<!-- This is displayed when all data is ready. -->
{{dstache}}#each notifications}}
{{dstache}}> notification}}
{{dstache}}/each}}
{{dstache}}else}}
Loading...
{{dstache}}/if}}
</template>
```
Another example where the subscription depends on the data context:
```js
Template.comments.onCreated(function () {
// Use this.subscribe with the data context reactively
this.autorun(() => {
var dataContext = Template.currentData();
this.subscribe("comments", dataContext.postId);
});
});
```
```html
{{dstache}}#with post}}
{{dstache}}> comments postId=_id}}
{{dstache}}/with}}
```
Another example where you want to initialize a plugin when the subscription is
done:
```js
Template.listing.onRendered(function () {
var template = this;
template.subscribe('listOfThings', () => {
// Wait for the data to load using the callback
Tracker.afterFlush(() => {
// Use Tracker.afterFlush to wait for the UI to re-render
// then use highlight.js to highlight a code snippet
highlightBlock(template.find('.code'));
});
});
});
```
{{> autoApiBox "Blaze.TemplateInstance#view"}}
{{> autoApiBox "Template.registerHelper"}}
{{> autoApiBox "Template.instance"}}
{{> autoApiBox "Template.currentData"}}
{{> autoApiBox "Template.parentData"}}
For example, `Template.parentData(0)` is equivalent to `Template.currentData()`. `Template.parentData(2)`
is equivalent to `{{dstache}}../..}}` in a template.
{{> autoApiBox "Template.body"}}
You can define helpers and event maps on `Template.body` just like on
any `Template.myTemplate` object.
Helpers on `Template.body` are only available in the `<body>` tags of
your app. To register a global helper, use
[Template.registerHelper](#template_registerhelper).
Event maps on `Template.body` don't apply to elements added to the
body via `Blaze.render`, jQuery, or the DOM API, or to the body element
itself. To handle events on the body, window, or document, use jQuery
or the DOM API.
{{> autoApiBox "Template.dynamic"}}
`Template.dynamic` allows you to include a template by name, where the name
may be calculated by a helper and may change reactively. The `data`
argument is optional, and if it is omitted, the current data context
is used. It's also possible, to use `Template.dynamic` as a block helper
(`{{dstache}}#Template.dynamic}} ... {{dstache}}/Template.dynamic}}`)
For example, if there is a template named "foo", `{{dstache}}> Template.dynamic
template="foo"}}` is equivalent to `{{dstache}}> foo}}` and
`{{dstache}}#Template.dynamic template="foo"}} ... {{dstache}}/Template.dynamic}}`
is equivalent to `{{dstache}}#foo}} ... {{dstache}}/foo}}`.
{{> apiBoxTitle name="Event Maps" id="eventmaps"}}
An event map is an object where
the properties specify a set of events to handle, and the values are
the handlers for those events. The property can be in one of several
forms:
<dl>
{{#dtdd "<em>eventtype</em>"}}
Matches a particular type of event, such as 'click'.
{{/dtdd}}
{{#dtdd "<em>eventtype selector</em>"}}
Matches a particular type of event, but only when it appears on
an element that matches a certain CSS selector.
{{/dtdd}}
{{#dtdd "<em>event1, event2</em>"}}
To handle more than one type of event with the same function, use a
comma-separated list.
{{/dtdd}}
</dl>
The handler function receives two arguments: `event`, an object with
information about the event, and `template`, a [template
instance](#template_inst) for the template where the handler is
defined. The handler also receives some additional context data in
`this`, depending on the context of the current element handling the
event. In a template, an element's context is the
data context where that element occurs, which is set by
block helpers such as `#with` and `#each`.
Example:
{
// Fires when any element is clicked
'click'(event) { ... },
// Fires when any element with the 'accept' class is clicked
'click .accept'(event) { ... },
// Fires when 'accept' is clicked or focused, or a key is pressed
'click .accept, focus .accept, keypress'(event) { ... }
}
Most events bubble up the document tree from their originating
element. For example, `'click p'` catches a click anywhere in a
paragraph, even if the click originated on a link, span, or some other
element inside the paragraph. The originating element of the event
is available as the `target` property, while the element that matched
the selector and is currently handling it is called `currentTarget`.
{
'click p'(event) {
var paragraph = event.currentTarget; // always a P
var clickedElement = event.target; // could be the P or a child element
}
}
If a selector matches multiple elements that an event bubbles to, it
will be called multiple times, for example in the case of `'click
div'` or `'click *'`. If no selector is given, the handler
will only be called once, on the original target element.
The following properties and methods are available on the event object
passed to handlers:
<dl class="objdesc">
{{#dtdd name="type" type="String"}}
The event's type, such as "click", "blur" or "keypress".
{{/dtdd}}
{{#dtdd name="target" type="DOM Element"}}
The element that originated the event.
{{/dtdd}}
{{#dtdd name="currentTarget" type="DOM Element"}}
The element currently handling the event. This is the element that
matched the selector in the event map. For events that bubble, it may
be `target` or an ancestor of `target`, and its value changes as the
event bubbles.
{{/dtdd}}
{{#dtdd name="which" type="Number"}}
For mouse events, the number of the mouse button (1=left, 2=middle, 3=right).
For key events, a character or key code.
{{/dtdd}}
{{#dtdd "stopPropagation()"}}
Prevent the event from propagating (bubbling) up to other elements.
Other event handlers matching the same element are still fired, in
this and other event maps.
{{/dtdd}}
{{#dtdd "stopImmediatePropagation()"}}
Prevent all additional event handlers from being run on this event,
including other handlers in this event map, handlers reached by
bubbling, and handlers in other event maps.
{{/dtdd}}
{{#dtdd "preventDefault()"}}
Prevents the action the browser would normally take in response to this
event, such as following a link or submitting a form. Further handlers
are still called, but cannot reverse the effect.
{{/dtdd}}
{{#dtdd "isPropagationStopped()"}}
Returns whether `stopPropagation()` has been called for this event.
{{/dtdd}}
{{#dtdd "isImmediatePropagationStopped()"}}
Returns whether `stopImmediatePropagation()` has been called for this event.
{{/dtdd}}
{{#dtdd "isDefaultPrevented()"}}
Returns whether `preventDefault()` has been called for this event.
{{/dtdd}}
</dl>
Returning `false` from a handler is the same as calling
both `stopImmediatePropagation` and `preventDefault` on the event.
Event types and their uses include:
<dl class="objdesc">
{{#dtdd "<code>click</code>"}}
Mouse click on any element, including a link, button, form control, or div.
Use `preventDefault()` to prevent a clicked link from being followed.
Some ways of activating an element from the keyboard also fire `click`.
{{/dtdd}}
{{#dtdd "<code>dblclick</code>"}}
Double-click.
{{/dtdd}}
{{#dtdd "<code>focus, blur</code>"}}
A text input field or other form control gains or loses focus. You
can make any element focusable by giving it a `tabindex` property.
Browsers differ on whether links, checkboxes, and radio buttons are
natively focusable. These events do not bubble.
{{/dtdd}}
{{#dtdd "<code>change</code>"}}
A checkbox or radio button changes state. For text fields, use
`blur` or key events to respond to changes.
{{/dtdd}}
{{#dtdd "<code>mouseenter, mouseleave</code>"}} The pointer enters or
leaves the bounds of an element. These events do not bubble.
{{/dtdd}}
{{#dtdd "<code>mousedown, mouseup</code>"}}
The mouse button is newly down or up.
{{/dtdd}}
{{#dtdd "<code>keydown, keypress, keyup</code>"}}
The user presses a keyboard key. `keypress` is most useful for
catching typing in text fields, while `keydown` and `keyup` can be
used for arrow keys or modifier keys.
{{/dtdd}}
</dl>
Other DOM events are available as well, but for the events above,
Meteor has taken some care to ensure that they work uniformly in all
browsers.
{{> apiBoxTitle name="Spacebars" id="spacebars"}}
Spacebars is the language used to write Meteor templates. It is inspired by [Handlebars](http://handlebarsjs.com/). It shares some of the spirit and syntax of Handlebars, but has been tailored to produce reactive Meteor templates when compiled.
For more information about Spacebars, see the [Spacebars README](#pkg_spacebars).
{{/template}}

View File

@@ -1,25 +0,0 @@
{{#template name="apiTimers"}}
<h2 id="timers"><span>Timers</span></h2>
Meteor uses global environment variables
to keep track of things like the current request's user. To make sure
these variables have the right values, you need to use
`Meteor.setTimeout` instead of `setTimeout` and `Meteor.setInterval`
instead of `setInterval`.
These functions work just like their native JavaScript equivalents.
If you call the native function, you'll get an error stating that Meteor
code must always run within a Fiber, and advising to use
`Meteor.bindEnvironment`.
{{> autoApiBox "Meteor.setTimeout"}}
Returns a handle that can be used by `Meteor.clearTimeout`.
{{> autoApiBox "Meteor.setInterval"}}
Returns a handle that can be used by `Meteor.clearInterval`.
{{> autoApiBox "Meteor.clearTimeout"}}
{{> autoApiBox "Meteor.clearInterval"}}
{{/template}}

View File

@@ -1,311 +0,0 @@
{{#template name="apiTracker"}}
<h2 id="tracker"><span>Tracker</span></h2>
Meteor has a simple dependency tracking system which allows it to
automatically rerun templates and other computations whenever
[`Session`](#session) variables, database queries, and other data
sources change.
Unlike most other systems, you don't have to manually declare these
dependencies &mdash; it "just works". The mechanism is simple and
efficient. When you call a function that supports reactive updates
(such as a database query), it automatically saves the current
Computation object, if any (representing, for example, the current
template being rendered). Later, when the data changes, the function
can "invalidate" the Computation, causing it to rerun (rerendering the
template).
Applications will find [`Tracker.autorun`](#tracker_autorun) useful, while more
advanced facilities such as `Tracker.Dependency` and `onInvalidate`
callbacks are intended primarily for package authors implementing new
reactive data sources.
{{> autoApiBox "Tracker.autorun" }}
`Tracker.autorun` allows you to run a function that depends on reactive data
sources, in such a way that if there are changes to the data later,
the function will be rerun.
For example, you can monitor a cursor (which is a reactive data
source) and aggregate it into a session variable:
Tracker.autorun(function () {
var oldest = _.max(Monkeys.find().fetch(), function (monkey) {
return monkey.age;
});
if (oldest)
Session.set("oldest", oldest.name);
});
Or you can wait for a session variable to have a certain value, and do
something the first time it does, calling `stop` on the computation to
prevent further rerunning:
Tracker.autorun(function (c) {
if (! Session.equals("shouldAlert", true))
return;
c.stop();
alert("Oh no!");
});
The function is invoked immediately, at which point it may alert and
stop right away if `shouldAlert` is already true. If not, the
function is run again when `shouldAlert` becomes true.
A change to a data dependency does not cause an immediate rerun, but
rather "invalidates" the computation, causing it to rerun the next
time a flush occurs. A flush will occur automatically as soon as
the system is idle if there are invalidated computations. You can
also use [`Tracker.flush`](#tracker_flush) to cause an immediate flush of
all pending reruns.
If you nest calls to `Tracker.autorun`, then when the outer call stops or
reruns, the inner call will stop automatically. Subscriptions and
observers are also automatically stopped when used as part of a
computation that is rerun, allowing new ones to be established. See
[`Meteor.subscribe`](#meteor_subscribe) for more information about
subscriptions and reactivity.
If the initial run of an autorun throws an exception, the computation
is automatically stopped and won't be rerun.
{{> autoApiBox "Tracker.flush" }}
Normally, when you make changes (like writing to the database),
their impact (like updating the DOM) is delayed until the system is
idle. This keeps things predictable &mdash; you can know that the DOM
won't go changing out from under your code as it runs. It's also one
of the things that makes Meteor fast.
`Tracker.flush` forces all of the pending reactive updates to complete.
For example, if an event handler changes a Session
variable that will cause part of the user interface to rerender, the
handler can call `flush` to perform the rerender immediately and then
access the resulting DOM.
An automatic flush occurs whenever the system is idle which performs
exactly the same work as `Tracker.flush`. The flushing process consists
of rerunning any invalidated computations. If additional
invalidations happen while flushing, they are processed as part of the
same flush until there is no more work to be done. Callbacks
registered with [`Tracker.afterFlush`](#tracker_afterflush) are called
after processing outstanding invalidations.
It is illegal to call `flush` from inside a `flush` or from a running
computation.
The <a href="http://manual.meteor.com/#tracker-theflushcycle">Meteor Manual</a>
describes the motivation for the flush cycle and the guarantees made by
`Tracker.flush` and `Tracker.afterFlush`.
{{> autoApiBox "Tracker.nonreactive" }}
Calls `func` with `Tracker.currentComputation` temporarily set to `null`
and returns `func`'s own return value. If `func` accesses reactive data
sources, these data sources will never cause a rerun of the enclosing
computation.
{{> autoApiBox "Tracker.active" }}
This value is useful for data source implementations to determine
whether they are being accessed reactively or not.
{{> autoApiBox "Tracker.currentComputation" }}
It's very rare to need to access `currentComputation` directly. The
current computation is used implicitly by
[`Tracker.active`](#tracker_active) (which tests whether there is one),
[`dependency.depend()`](#dependency_depend) (which registers that it depends on a
dependency), and [`Tracker.onInvalidate`](#tracker_oninvalidate) (which
registers a callback with it).
{{> autoApiBox "Tracker.onInvalidate" }}
See [*`computation`*`.onInvalidate`](#computation_oninvalidate) for more
details.
{{> autoApiBox "Tracker.afterFlush" }}
Functions scheduled by multiple calls to `afterFlush` are guaranteed
to run in the order that `afterFlush` was called. Functions are
guaranteed to be called at a time when there are no invalidated
computations that need rerunning. This means that if an `afterFlush`
function invalidates a computation, that computation will be rerun
before any other `afterFlush` functions are called.
<h2 id="tracker_computation"><span>Tracker.Computation</span></h2>
A Computation object represents code that is repeatedly rerun in
response to reactive data changes. Computations don't have return
values; they just perform actions, such as rerendering a template on
the screen. Computations are created using [`Tracker.autorun`](#tracker_autorun).
Use [`stop`](#computation_stop) to prevent further rerunning of a
computation.
Each time a computation runs, it may access various reactive data
sources that serve as inputs to the computation, which are called its
dependencies. At some future time, one of these dependencies may
trigger the computation to be rerun by invalidating it. When this
happens, the dependencies are cleared, and the computation is
scheduled to be rerun at flush time.
The *current computation*
([`Tracker.currentComputation`](#tracker_currentcomputation)) is the
computation that is currently being run or rerun (computed), and the
one that gains a dependency when a reactive data source is accessed.
Data sources are responsible for tracking these dependencies using
[`Tracker.Dependency`](#tracker_dependency) objects.
Invalidating a computation sets its `invalidated` property to true
and immediately calls all of the computation's `onInvalidate`
callbacks. When a flush occurs, if the computation has been invalidated
and not stopped, then the computation is rerun by setting the
`invalidated` property to `false` and calling the original function
that was passed to `Tracker.autorun`. A flush will occur when the current
code finishes running, or sooner if `Tracker.flush` is called.
Stopping a computation invalidates it (if it is valid) for the purpose
of calling callbacks, but ensures that it will never be rerun.
Example:
// if we're in a computation, then perform some clean-up
// when the current computation is invalidated (rerun or
// stopped)
if (Tracker.active) {
Tracker.onInvalidate(function () {
x.destroy();
y.finalize();
});
}
{{> autoApiBox "Tracker.Computation#stop"}}
Stopping a computation is irreversible and guarantees that it will
never be rerun. You can stop a computation at any time, including
from the computation's own run function. Stopping a computation that
is already stopped has no effect.
Stopping a computation causes its `onInvalidate` callbacks to run
immediately if it is not currently invalidated, as well as its
`stop` callbacks.
Nested computations are stopped automatically when their enclosing
computation is rerun.
{{> autoApiBox "Tracker.Computation#invalidate" }}
Invalidating a computation marks it to be rerun at
[flush time](#tracker_flush), at
which point the computation becomes valid again. It is rare to
invalidate a computation manually, because reactive data sources
invalidate their calling computations when they change. Reactive data
sources in turn perform this invalidation using one or more
[`Tracker.Dependency`](#tracker_dependency) objects.
Invalidating a computation immediately calls all `onInvalidate`
callbacks registered on it. Invalidating a computation that is
currently invalidated or is stopped has no effect. A computation can
invalidate itself, but if it continues to do so indefinitely, the
result will be an infinite loop.
{{> autoApiBox "Tracker.Computation#onInvalidate" }}
`onInvalidate` registers a one-time callback that either fires
immediately or as soon as the computation is next invalidated or
stopped. It is used by reactive data sources to clean up resources or
break dependencies when a computation is rerun or stopped.
To get a callback after a computation has been recomputed, you can
call [`Tracker.afterFlush`](#tracker_afterflush) from `onInvalidate`.
{{> autoApiBox "Tracker.Computation#onStop" }}
{{> autoApiBox "Tracker.Computation#stopped" }}
{{> autoApiBox "Tracker.Computation#invalidated" }}
This property is initially false. It is set to true by `stop()` and
`invalidate()`. It is reset to false when the computation is
recomputed at flush time.
{{> autoApiBox "Tracker.Computation#firstRun" }}
This property is a convenience to support the common pattern where a
computation has logic specific to the first run.
<h2 id="tracker_dependency"><span>Tracker.Dependency</span></h2>
A Dependency represents an atomic unit of reactive data that a
computation might depend on. Reactive data sources such as Session or
Minimongo internally create different Dependency objects for different
pieces of data, each of which may be depended on by multiple
computations. When the data changes, the computations are
invalidated.
Dependencies don't store data, they just track the set of computations to
invalidate if something changes. Typically, a data value will be
accompanied by a Dependency object that tracks the computations that depend
on it, as in this example:
var weather = "sunny";
var weatherDep = new Tracker.Dependency;
var getWeather = function () {
weatherDep.depend()
return weather;
};
var setWeather = function (w) {
weather = w;
// (could add logic here to only call changed()
// if the new value is different from the old)
weatherDep.changed();
};
This example implements a weather data source with a simple getter and
setter. The getter records that the current computation depends on
the `weatherDep` dependency using `depend()`, while the setter
signals the dependency to invalidate all dependent computations by
calling `changed()`.
The reason Dependencies do not store data themselves is that it can be
useful to associate multiple Dependencies with the same piece of data.
For example, one Dependency might represent the result of a database
query, while another might represent just the number of documents in
the result. A Dependency could represent whether the weather is sunny
or not, or whether the temperature is above freezing.
[`Session.equals`](#session_equals) is implemented this way for
efficiency. When you call `Session.equals("weather", "sunny")`, the
current computation is made to depend on an internal Dependency that
does not change if the weather goes from, say, "rainy" to "cloudy".
Conceptually, the only two things a Dependency can do are gain a
dependent and change.
A Dependency's dependent computations are always valid (they have
`invalidated === false`). If a dependent is invalidated at any time,
either by the Dependency itself or some other way, it is immediately
removed.
See the <a href="http://manual.meteor.com/#tracker-reactivevaluewithdependency">
Meteor Manual</a> to learn how to create a reactive data source using
Tracker.Dependency.
{{> autoApiBox "Tracker.Dependency#changed" }}
{{> autoApiBox "Tracker.Dependency#depend" }}
`dep.depend()` is used in reactive data source implementations to record
the fact that `dep` is being accessed from the current computation.
{{> autoApiBox "Tracker.Dependency#hasDependents" }}
For reactive data sources that create many internal Dependencies,
this function is useful to determine whether a particular Dependency is
still tracking any dependency relationships or if it can be cleaned up
to save memory.
{{/template}}

View File

@@ -1,370 +0,0 @@
<template name="commandline">
<div>
{{#markdown}}
<h1 id="commandline">Command line</h1>
The following are some of the more commonly used commands in the `meteor`
command-line tool. This is just an overview and does not mention every command
or every option to every command; for more details, use the `meteor help`
command.
<!-- XXX some intro text? -->
<h3 id="meteorhelp">meteor help</h3>
Get help on meteor command line usage. Running `meteor help` by
itself will list the common meteor
commands. Running <code>meteor help <i>command</i></code> will print
detailed help about the command.
<h3 id="meteorrun">meteor run</h3>
Run a meteor development server in the current project. Searches
upward from the current directory for the root directory of a Meteor
project. Whenever you change any of the application's source files, the
changes are automatically detected and applied to the running
application.
You can use the application by pointing your web browser at
<a href="http://localhost:3000">localhost:3000</a>. No Internet connection is
required.
This is the default command. Simply running `meteor` is the
same as `meteor run`.
To pass additional options to Node.js use the `NODE_OPTIONS` environment variable.
For example: `NODE_OPTIONS='--debug'` or `NODE_OPTIONS='--debug-brk'`
Run `meteor help run` to see the full list of options.
<h3 id="meteordebug">meteor debug</h3>
Run the project, but suspend the server process for debugging.
The server process will be suspended just before the first statement of
server code that would normally execute. In order to continue execution of
server code, use either the web-based Node Inspector or the command-line
debugger (further instructions will be printed in the console).
Breakpoints can be set using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger" target="_blank">`debugger`
keyword</a>, or through the web UI of Node Inspector ("Sources" tab).
The server process debugger will listen for incoming connections from
debugging clients, such as node-inspector, on port 5858 by default. To
specify a different port use the `--debug-port <port>` option.
The same debugging functionality can be achieved by adding the `--debug-port <port>`
option to other `meteor` tool commands, such as `meteor run` and `meteor test-packages`.
<h3 id="meteorcreate">meteor create <i>name</i></h3>
Create a new Meteor project. By default, makes a subdirectory named *name*
and copies in the template app. You can pass an absolute or relative
path.
You can use the `--package` option, to create a new package. If used in an
existing app, this command will create a package in the packages
directory.
<h3 id="meteorloginlogout">meteor login / logout</h3>
Log in and out of your account using Meteor's authentication system.
You can pass `METEOR_SESSION_FILE=token.json` before `meteor login` to generate
a login session token so you don't have to share your login credentials with
third-party service providers. You can revoke the token at any time from your
[accounts settings page](https://www.meteor.com/account-settings/login-locations).
Once you have your account you can log in and log out from the command line, and
check your username with `meteor whoami`.
<h3 id="meteordeploy">meteor deploy <i>site</i></h3>
Deploy the project in your current directory to
<a href="https://www.meteor.com/galaxy" target="_blank">Galaxy</a>.
You can deploy in debug mode by passing `--debug`. This
will leave your source code readable by your favorite in-browser
debugger, just like it is in local development mode.
To delete an application you've deployed, specify
the `--delete` option along with the site.
You can add information specific to a particular deployment of your application
by using the `--settings` option. The argument to `--settings` is a file
containing any JSON string. The object in your settings file will appear on the
server side of your application in [`Meteor.settings`](#meteor_settings).
Settings are persistent. When you redeploy your app, the old value will be
preserved unless you explicitly pass new settings using the `--settings` option.
To unset `Meteor.settings`, pass an empty settings file.
<h3 id="meteorupdate">meteor update</h3>
Attempts to bring you to the latest version of Meteor, and then to upgrade your
packages to their latest versions. By default, update will not break
compatibility.
For example, let's say packages A and B both depend on version 1.1.0 of package
X. If a new version of A depends on X@2.0.0, but there is no new version of
package B, running `meteor update` will not update A, because doing so will
break package B.
You can pass in the flag `--packages-only` to update only the packages, and not
the release itself. Similarly, you can pass in names of packages
(`meteor update foo:kittens baz:cats`) to only update specific packages.
Every project is pinned to a specific release of Meteor. You can temporarily try
using your package with another release by passing the `--release` option to any
command; `meteor update` changes the pinned release.
Sometimes, Meteor will ask you to run `meteor update --patch`. Patch releases
are special releases that contain only very minor changes (usually crucial bug
fixes) from previous releases. We highly recommend that you always run `update
--patch` when prompted.
You may also pass the `--release` flag to act as an override to update to a
specific release. This is an override: if it cannot find compatible versions of
packages, it will log a warning, but perform the update anyway. This will only
change your package versions if necessary.
<h3 id="meteoradd">meteor add <i>package</i></h3>
Add packages to your Meteor project. By convention, names of community packages
include the name of the maintainer. For example: `meteor add iron:router`. You
can add multiple packages with one command.
Optionally, adds version constraints. Running `meteor add package@1.1.0` will
add the package at version `1.1.0` or higher (but not `2.0.0` or higher). If you
want to use version `1.1.0` exactly, use `meteor add package@=1.1.0`. You can also
'or' constraints together: for example, `meteor add 'package@=1.0.0 || =2.0.1'`
means either 1.0.0 (exactly) or 2.0.1 (exactly).
To remove a version constraint for a specific package, run `meteor add` again
without specifying a version. For example above, to stop using version `1.1.0`
exactly, run `meteor add package`.
<h3 id="meteorremove">meteor remove <i>package</i></h3>
Removes a package previously added to your Meteor project. For a
list of the packages that your application is currently using, run
`meteor list`.
This removes the package entirely. To continue using the package,
but remove its version constraint, use [`meteor add`](#meteoradd).
Meteor does not downgrade transitive dependencies unless it's necessary. This
means that if running `meteor add A` upgrades A's parent package X to a new
version, your project will continue to use X at the new version even after you
run `meteor remove A`.
<h3 id="meteorlist">meteor list</h3>
Lists all the packages that you have added to your project. For each package,
lists the version that you are using. Lets you know if a newer version of that
package is available.
<h3 id="meteoraddplatform">meteor add-platform <i>platform</i></h3>
Adds platforms to your Meteor project. You can add multiple
platforms with one command. Once a platform has been added, you
can use 'meteor run <i>platform</i>' to run on the platform, and `meteor build`
to build the Meteor project for every added platform.
<h3 id="meteorremoveplatform">meteor remove-platform <i>platform</i></h3>
Removes a platform previously added to your Meteor project. For a
list of the platforms that your application is currently using, see
`meteor list-platforms`.
<h3 id="meteorlistplatforms">meteor list-platforms</h3>
Lists all of the platforms that have been explicitly added to your project.
<h3 id="meteormongo">meteor mongo</h3>
Open a MongoDB shell on your local development database, so that you
can view or manipulate it directly.
{{#warning}}
For now, you must already have your application running locally
with `meteor run`. This will be easier in the future.
{{/warning}}
<h3 id="meteorreset">meteor reset</h3>
Reset the current project to a fresh state. Removes the local
mongo database.
{{#warning}}
This deletes your data! Make sure you do not have any information you
care about in your local mongo database by running `meteor mongo`.
From the mongo shell, use `show collections`
and <code>db.<i>collection</i>.find()</code> to inspect your data.
{{/warning}}
{{#warning}}
For now, you can not run this while a development server is
running. Quit all running meteor applications before running this.
{{/warning}}
<h3 id="meteorbuild">meteor build</h3>
Package this project up for deployment. The output is a directory with several
build artifacts:
<ul><li>a tarball that includes everything necessary to run the application server
(see the <code>README</code> in the tarball for details)</li>
<li>an unsigned <code>apk</code> bundle and a project source if Android is targetted as a
mobile platform</li>
<li>a directory with an Xcode project source if iOS is targetted as a mobile
platform</li></ul>
You can use the application server bundle to host a Meteor application on your
own server, instead of deploying to Galaxy. You will have to deal
with logging, monitoring, backups, load-balancing, etc, all of which we handle
for you if you use Galaxy.
The unsigned `apk` bundle and the outputted Xcode project can be used to deploy
your mobile apps to Android Play Store and Apple App Store.
By default, your application is bundled for your current architecture.
This may cause difficulties if your app contains binary code due to,
for example, npm packages. You can try to override that behavior
with the `--architecture` flag.
<h3 id="meteorlint">meteor lint</h3>
Run through the whole build process for the app and run all linters the app
uses. Outputs all build errors or linting warnings to the standard output.
<h3 id="meteorsearch">meteor search</h3>
Searches for Meteor packages and releases, whose names contain the specified
regular expression.
<h3 id="meteorshow">meteor show</h3>
Shows more information about a specific package or release: name, summary, the
usernames of its maintainers, and, if specified, its homepage and git URL.
<h3 id="meteorpublish">meteor publish</h3>
Publishes your package. To publish, you must `cd` into the package directory, log
in with your Meteor Developer Account and run `meteor publish`. By convention,
published package names must begin with the maintainer's Meteor Developer
Account username and a colon, like so: `iron:router`.
To publish a package for the first time, use `meteor publish --create`.
Sometimes packages may contain binary code specific to an architecture (for
example, they may use an npm package). In that case, running publish will only
upload the build to the architecture that you were using to publish it. You can
use `publish-for-arch` to upload a build to a different architecture from a
different machine.
<h3 id="meteorpublishforarch">meteor publish-for-arch</h3>
Publishes a build of an existing package version from a different architecture.
Some packages contain code specific to an architecture. Running `publish` by
itself, will upload the build to the architecture that you were using to
publish. You need to run `publish-for-arch` from a different architecture to
upload a different build.
For example, let's say you published name:cool-binary-blob from a Mac. If you
want people to be able to use cool-binary-blob from Linux, you should log into a
Linux machine and then run
`meteor publish-for-arch name:cool-binary-blob@version`. It will notice that you
are on a linux machine, and that there is no Linux-compatible build for your package
and publish one.
Currently, the supported architectures for Meteor are 32-bit Linux, 64-bit Linux
and Mac OS. Galaxy's servers run 64-bit Linux.
<h3 id="meteorpublishrelease">meteor publish-release</h3>
Publishes a release of Meteor. Takes in a JSON configuration file.
Meteor releases are divided into tracks. While only MDG members can publish to
the default Meteor track, anyone can create a track of their own and publish to
it. Running `meteor update` without specifying the `--release` option will not
cause the user to switch tracks.
To publish to a release track for the first time, use the `--create-track` flag.
The JSON configuration file must contain the name of the release track
(`track`), the release version (`version`), various metadata, the packages
specified by the release as mapped to versions (`packages`), and the package &
version of the Meteor command-line tool (`tool`). Note that this means that
forks of the meteor tool can be published as packages and people can use them by
switching to a corresponding release. For more information, run
`meteor help publish-release`.
<h3 id="meteortestpackages">meteor test-packages</h3>
Test Meteor packages, either by name, or by directory. Not specifying an
argument will run tests for all local packages. The results are displayed in an
app that runs at `localhost:3000` by default. If you need to, you can pass the
`--settings` and `--port` arguments.
<h3 id="meteoradmin">meteor admin</h3>
Catch-all for miscellaneous commands that require authorization to use.
Some example uses of `meteor admin` include adding and removing package
maintainers and setting a homepage for a package. It also includes various
helpful functions for managing a Meteor release. Run `meteor help admin` for
more information.
<h3 id="meteorshell">meteor shell</h3>
When `meteor shell` is executed in an application directory where a server
is already running, it connects to the server and starts an interactive
shell for evaluating server-side code.
Multiple shells can be attached to the same server. If no server is
currently available, `meteor shell` will keep trying to connect until it
succeeds.
Exiting the shell does not terminate the server. If the server restarts
because a change was made in server code, or a fatal exception was
encountered, the shell will restart along with the server. This behavior
can be simulated by typing `.reload` in the shell.
The shell supports tab completion for global variables like `Meteor`,
`Mongo`, and `Package`. Try typing `Meteor.is` and then pressing tab.
The shell maintains a persistent history across sessions. Previously-run
commands can be accessed by pressing the up arrow.
{{/markdown}}
</div>
</template>

View File

@@ -1,588 +0,0 @@
<template name="concepts">
<h1 id="concepts">Concepts</h1>
{{> structure }}
{{> data_ }}
{{> reactivity }}
{{> livehtmltemplates }}
{{> packages_concept }}
{{> namespacing }}
{{> deploying }}
{{> packages_writing }}
</template>
<template name="structure">
{{#markdown}}
<h2 id="structuringyourapp">Structuring your application</h2>
A Meteor application is a mix of client-side JavaScript that runs inside a web
browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor
server inside a [Node.js](http://nodejs.org/) container, and all the supporting
HTML templates, CSS rules, and static assets. Meteor automates the packaging
and transmission of these different components, and it is quite flexible about
how you choose to structure those components in your file tree.
### Special Directories
By default, any JavaScript files in your Meteor folder are bundled and sent to
the client and the server. However, the names of the files and directories
inside your project can affect their load order, where they are loaded, and some
other characteristics. Here is a list of file and directory names that are
treated specially by Meteor:
- **client**
Any directory named `client` is not loaded on the server. Similar to
wrapping your code in `if (Meteor.isClient) { ... }`. All files loaded on
the client are automatically concatenated and minified when in production
mode. In development mode, JavaScript and CSS files are not minified, to
make debugging easier. (CSS files are still combined into a single file
for consistency between production and development, because changing the
CSS file's URL affects how URLs in it are processed.)
HTML files in a Meteor application are treated quite a bit differently
from a server-side framework. Meteor scans all the HTML files in your
directory for three top-level elements: `<head>`, `<body>`, and
`<template>`. The head and body sections are separately concatenated
into a single head and body, which are transmitted to the client on
initial page load.
- **server**
Any directory named `server` is not loaded on the client. Similar to
wrapping your code in `if (Meteor.isServer) { ... }`, except the client
never even receives the code. 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 gathers all your JavaScript files, excluding anything under the
`client`, `public`, and `private` subdirectories, and loads them into a
Node.js server instance. In Meteor, your server code runs in a single
thread per request, not in the asynchronous callback style typical of Node.
We find the linear execution model a better fit for the typical server code
in a Meteor application.
- **public**
All files inside a top-level directory called `public` are served as-is to
the client. When referencing these assets, do not include `public/` in the
URL, write the URL as if they were all in the top level. For example,
reference `public/bg.png` as `<img src='/bg.png' />`. This is the best place
for `favicon.ico`, `robots.txt`, and similar files.
- **private**
All files inside a top-level directory called `private` are only accessible
from server code and can be loaded via the [`Assets`](#assets) API. This can
be used for private data files and any files that are in your project
directory that you don't want to be accessible from the outside.
- **client/compatibility**
This folder is for compatibility JavaScript libraries that rely on variables
declared with var at the top level being exported as globals. Files in this
directory are executed without being wrapped in a new variable scope. These
files are executed before other client-side JavaScript files.
- **tests**
Any directory named `tests` is not loaded anywhere. Use this for any local
test code.
- **node_modules**
For compatibility with node.js tools used alongside Meteor, any directory named
`node_modules` is not loaded anywhere. node.js packages installed into
`node_modules` directories will not be available to your Meteor code. Use
`Npm.depends` in your package `package.js` file for that.
The following directories are also not loaded as part of your app code:
- Files/directories whose names start with a dot, like `.meteor` and `.git`
- `packages/`: Used for local packages, covered below
- `programs`: For legacy reasons
- [`cordova-build-override`](https://github.com/meteor/meteor/wiki/Meteor-Cordova-Phonegap-integration#advanced-build-customization)
### Files outside special directories
All JavaScript files outside special directories are loaded on both the client
and the server. That's the place for model definitions and other functions.
Meteor provides the variables [`Meteor.isClient`](#meteor_isclient) and
[`Meteor.isServer`](#meteor_isserver) so that your code can alter its behavior
depending on whether it's running on the client or the server.
CSS and HTML files outside special directories are loaded on the client only,
and cannot be used from server code.
### Example File Structure
The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above.
```bash
lib/ # common code like collections and utilities
lib/methods.js # Meteor.methods definitions
lib/constants.js # constants used in the rest of the code
client/compatibility # legacy libraries that expect to be global
client/lib/ # code for the client to be loaded first
client/lib/helpers.js # useful helpers for your client code
client/body.html # content that goes in the <body> of your HTML
client/head.html # content for <head> of your HTML: <meta> tags, etc
client/style.css # some CSS code
client/<feature>.html # HTML templates related to a certain feature
client/<feature>.js # JavaScript code related to a certain feature
server/lib/permissions.js # sensitive permissions code used by your server
server/publications.js # Meteor.publish definitions
public/favicon.ico # app icon
settings.json # configuration data to be passed to meteor --settings
mobile-config.js # define icons and metadata for Android/iOS
```
You can also model your directory structure after the example apps. Run `meteor
create --example todos` and explore the directories to see where all the files
in a real app could go.
### File Load Order
It is best to write your application in such a way that it is insensitive to
the order in which files are loaded, for example by using [Meteor.startup](#meteor_startup),
or by moving load order sensitive code into [packages](#usingpackages),
which can explicitly control both the load order of their contents and their
load order with respect to other packages. However, sometimes load order
dependencies in your application are unavoidable.
There are several load ordering rules. They are *applied sequentially* to all
applicable files in the application, in the priority given below:
1. HTML template files are *always* loaded before everything else
2. Files beginning with `main.` are loaded last
3. Files inside *any* `lib/` directory are loaded next
4. Files with deeper paths are loaded next
5. Files are then loaded in alphabetical order of the entire path
```js
nav.html
main.html
client/lib/methods.js
client/lib/styles.js
lib/feature/styles.js
lib/collections.js
client/feature-y.js
feature-x.js
client/main.js
```
For example, the files above are arranged in the correct load order.
`main.html` is loaded second because HTML templates are always loaded first,
even if it begins with `main.`, since rule 1 has priority over rule 2.
However, it will be loaded after `nav.html` because rule 2 has priority over
rule 5.
`client/lib/styles.js` and `lib/feature/styles.js` have identical load order
up to rule 4; however, since `client` comes before `lib` alphabetically,
it will be loaded first.
### Organizing Your Project
There are three main ways to organize your files into features or components.
Let's say we have two types of objects in our project: **apples** and
**oranges**.
#### Method 1: Root-Level Folders
Since the special `client`, `server`, and `lib` directories work if they are
anywhere in the path, you can use top-level folders to organize code into
modules:
```bash
apples/lib/ # code for apple-related features
apples/client/
apples/server/
oranges/lib/ # code for orange-related features
oranges/client/
oranges/server/
```
#### Method 2: Folders inside client/ and server/
```bash
lib/apples/ # common code for apples
lib/oranges/ # and oranges
client/apples/ # client code for apples
client/oranges/ # and oranges
server/apples/ # server code for apples
server/oranges/ # and oranges
```
#### Method 3: Packages
This is the ultimate in code separation, modularity, and reusability. If you put
the code for each feature in a separate package, the code for one feature won't
be able to access the code for the other feature except through exports, making
every dependency explicit. This also allows for the easiest independent testing
of features. You can also publish the packages and use them in multiple apps
with `meteor add`.
```bash
packages/apples/package.js # files, dependencies, exports for apple feature
packages/apples/<anything>.js # file loading is controlled by package.js
packages/oranges/package.js # files, dependencies, exports for orange feature
packages/oranges/<anything>.js # file loading is controlled by package.js
```
{{/markdown}}
</template>
<template name="data_">
{{#markdown}}
<a id="dataandsecurity-validation"></a>
<h2 id="dataandsecurity">Data and security</h2>
To read about best practices for managing data and security in Meteor, consult the Meteor Guide:
- [Security](http://guide.meteor.com/security.html)
- [Database collections](http://guide.meteor.com/collections.html)
- [Data loading](http://guide.meteor.com/data-loading.html)
- [Methods and saving data](http://guide.meteor.com/methods.html)
<h3 id="dataandsecurity-authentication">Authentication and user accounts</h3>
Meteor includes [Meteor Accounts](#accounts_api), a state-of-the-art
authentication system. It features secure password login using the
[bcrypt](http://en.wikipedia.org/wiki/Bcrypt) algorithm,
and integration with external services including Facebook, GitHub,
Google, Meetup, Twitter, and Weibo. Meteor Accounts defines a
[`Meteor.users`](#meteor_users) collection where developers can store
application-specific user data.
Meteor also includes pre-built forms for common tasks like login, signup,
password change, and password reset emails. You can add [Accounts
UI](#accountsui) to your app with just one line of code. The `accounts-ui` package even provides a configuration wizard that walks you through the steps to
set up the external login services you're using in your app.
[Read about how to manage user accounts in your Meteor app in the Meteor Guide.](http://guide.meteor.com/accounts.html)
{{/markdown}}
</template>
<template name="reactivity">
{{#markdown}}
<h2 id="reactivity">Reactivity</h2>
Meteor embraces the concept of [reactive
programming](http://en.wikipedia.org/wiki/Reactive_programming). This means that
you can write your code in a simple imperative style, and the result will be
automatically recalculated whenever data changes that your code depends on.
Tracker.autorun(function () {
Meteor.subscribe("messages", Session.get("currentRoomId"));
});
This example (taken from a chat room client) sets up a data
subscription based on the session variable `currentRoomId`.
If the value of `Session.get("currentRoomId")` changes for any reason, the
function will be automatically re-run, setting up a new subscription that
replaces the old one.
This automatic recomputation is achieved by a cooperation between
`Session` and `Tracker.autorun`. `Tracker.autorun` performs an arbitrary "reactive
computation" inside of which data dependencies are tracked, and it
will re-run its function argument as necessary. Data providers like
`Session`, on the other hand, make note of the computation they are
called from and what data was requested, and they are prepared to send
an invalidation signal to the computation when the data changes.
This simple pattern (reactive computation + reactive data source) has wide
applicability. Above, the programmer is saved from writing
unsubscribe/resubscribe calls and making sure they are called at the
right time. In general, Meteor can eliminate whole classes of data
propagation code which would otherwise clog up your application with
error-prone logic.
These Meteor functions run your code as a reactive computation:
* [Templates](#livehtmltemplates)
* [`Tracker.autorun`](#tracker_autorun)
* [`Template.autorun`](#template_autorun)
* [`Blaze.render`](#blaze_render) and [`Blaze.renderWithData`](#blaze_renderwithdata)
And the reactive data sources that can trigger changes are:
* [`Session`](#session) variables
* Database queries on [Collections](#find)
* [`Meteor.status`](#meteor_status)
* The `ready()` method on a [subscription handle](#meteor_subscribe)
* [`Meteor.user`](#meteor_user)
* [`Meteor.userId`](#meteor_userid)
* [`Meteor.loggingIn`](#meteor_loggingin)
In addition, the following functions which return an object with a
`stop` method, if called from a reactive computation, are stopped when
the computation is rerun or stopped:
* [`Tracker.autorun`](#tracker_autorun) (nested)
* [`Meteor.subscribe`](#meteor_subscribe)
* [`observe()`](#observe) and [`observeChanges()`](#observe_changes) on cursors
Meteor's
[implementation](https://github.com/meteor/meteor/blob/master/packages/tracker/tracker.js)
is a package called [`Tracker`](#tracker) that is fairly short and straightforward.
You can use it yourself to implement new reactive data sources.
{{/markdown}}
</template>
<template name="livehtmltemplates">
{{#markdown}}
<h2 id="livehtmltemplates">Live HTML templates</h2>
HTML templating is central to web applications. With Blaze, Meteor's live
page update technology, you can render your HTML _reactively_, meaning
that it will update automatically to track changes in the data used to
generate it.
[Read about how to use Blaze in the Meteor Guide.](http://guide.meteor.com/blaze.html)
{{/markdown}}
</template>
<template name="packages_concept">
{{#markdown}}
<h2 id="usingpackages">Using packages</h2>
All of the functionality you've read about so far is implemented in standard
Meteor packages. This is possible thanks to Meteor's unusually powerful
isomorphic package and build system. Isomorphic means the same packages work in
the web browser, in mobile apps, and on the server. Packages can also contain
plugins that extend the build process, such as `coffeescript`
([CoffeeScript](http://coffeescript.org) compilation) or `templating` (compiling
HTML templates).
Anyone can publish a Meteor package, and thousands of community-written packages
have been published to date. The easiest way to browse these packages is
<a href="http://www.atmospherejs.com">Atmosphere</a>, by Percolate Studio.
You can also use the [`meteor search`](#meteorsearch) and
[`meteor show`](#meteorshow) commands.
You can add packages to your project with [`meteor add`](#meteoradd) and remove
them with [`meteor remove`](#meteorremove).
Additionally, [`meteor list`](#meteorlist) will tell you what
packages your project is using, and [`meteor update`](#meteorupdate)
will update them to the newest versions when possible.
By default all apps include the `meteor-base` package. This pulls in the
packages that make up the core of the Meteor stack. Most apps will have this
package.
All new apps also start with a set of packages that allow a friendly development
experience. For more information about these packages, check out the comments in
the [packages file](https://github.com/meteor/meteor/blob/master/tools/skel/.meteor/packages).
Meteor uses a single-loading packaging system, meaning that it loads just one
version of every package. Before adding or upgrading to a particular version of
a package, Meteor uses a constraint solver to check if doing so will cause
other packages to break. By default, Meteor will choose conservatively. When
adding transitive dependencies (packages that other packages, but not the
application itself) depend on, Meteor will try to choose the earlier version.
In addition to the packages in the official Meteor release being used by your
app, `meteor list` and `meteor add` also search the `packages` directory at the
top of your app. You can also use the `packages` directory to break your app
into subpackages for your convenience, or to test packages that you might want
to publish. See [Writing Packages](#writingpackages). If you wish to add
packages outside of your app's folder structure, set the environment variable
`PACKAGE_DIRS` to a colon-delimited list of paths.
{{/markdown}}
</template>
<template name="namespacing">
{{#markdown}}
<h2 id="namespacing">Namespacing</h2>
Meteor's namespacing support makes it easy to write large applications
in JavaScript. Each package that you use in your app exists in its own
separate namespace, meaning that it sees only its own global variables
and any variables provided by the packages that it specifically
uses. Here's how it works.
When you declare a top-level variable, you have a choice. You can make
the variable File Scope or Package Scope.
// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};
// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};
Notice that this is just the normal JavaScript syntax for declaring a
variable that is local or global. Meteor scans your source code for
global variable assignments and generates a wrapper that makes sure
that your globals don't escape their appropriate namespace.
In addition to File Scope and Package Scope, there are also
Exports. An export is a variable that a package makes available to you
when you use it. For example, the `email` package exports the `Email`
variable. If your app uses the `email` package (and _only_ if it uses
the `email` package!) then your app can see `Email` and you can call
`Email.send`. Most packages have only one export, but some packages
might have two or three (for example, a package that provides several
classes that work together).
You see only the exports of the packages that you use directly. If you
use package A, and package A uses package B, then you only see package
A's exports. Package B's exports don't "leak" into your namespace just
because you used package A. This keeps each namespace nice and
tidy. Each app or package only sees their own globals plus the APIs of
the packages that they specifically asked for.
When debugging your app, your browser's JavaScript console behaves as
if it were attached to your app's namespace. You see your app's
globals and the exports of the packages that your app uses
directly. You don't see the variables from inside those packages, and
you don't see the exports of your transitive dependencies (packages
that aren't used directly by your app, but that are used by packages
that are used by your app).
If you want to look inside packages from inside your in-browser
debugger, you've got two options:
* Set a breakpoint inside package code. While stopped on that
breakpoint, the console will be in the package's namespace. You'll
see the package's package-scope variables, imports, and also any
file-scope variables for the file you're stopped in.
* If a package `foo` is included in your app, regardless of whether
your app uses it directly, its exports are available in
`Package.foo`. For example, if the `email` package is loaded, then
you can access `Package.email.Email.send` even from namespaces that
don't use the `email` package directly.
When declaring functions, keep in mind that `function x () {}` is just
shorthand for `var x = function x () {}` in JavaScript. Consider these
examples:
// This is the same as 'var x = function x () ...'. So x() is
// file-scope and can be called only from within this one file.
function x () { ... }
// No 'var', so x() is package-scope and can be called from
// any file inside this app or package.
x = function () { ... }
{{#note}}
Technically speaking, globals in an app (as opposed to in a package)
are actually true globals. They can't be captured in a scope that is
private to the app code, because that would mean that they wouldn't be
visible in the console during debugging! This means that app globals
actually end up being visible in packages. That should never be a
problem for properly written package code (since the app globals will
still be properly shadowed by declarations in the packages). You
certainly shouldn't depend on this quirk, and in the future Meteor may
check for it and throw an error if you do.
{{/note}}
{{/markdown}}
</template>
<template name="deploying">
{{#markdown}}
<h2 id="deploying">Deploying</h2>
To learn how to deploy Meteor apps, read the
[deployment article in the Meteor Guide](http://guide.meteor.com/deployment.html).
{{/markdown}}
</template>
<template name="packages_writing">
{{#markdown}}
<h2 id="writingpackages">Writing packages</h2>
Writing Meteor packages is easy. To initialize a meteor package, run
`meteor create --package username:packagename`, where `username` is your Meteor
Developer username. This will create a package from scratch and prefill the
directory with a package.js control file and some javascript. By default, Meteor
will take the package name from the name of the directory that contains the
package.js file. Don't forget to run `meteor add [packagename]`, even if the
package is internal to the app, in order to use it.
Meteor promises repeatable builds for both packages and applications. This means
that, if you built your package on a machine, then checked the code into a
repository and checked it out elsewhere, you should get the same result. In your
package directory, you will find an automatically generated `.versions`
file. This file specifies the versions of all packages used to build your
package and is part of the source. Check it into version control to ensure
repeatable builds across machines.
{{#note}}
Sometimes, packages do not just stand on their own, but function in the context
of an app (specifically, packages in the packages directory of an app). In that
case, the app's context will take precedence. Rather than using the
`.versions` file as a guide, we will build the package with the same
dependencies as used by the app (we think that, in practice, it would be
confusing to find your local packages built with different versions of
things).
{{/note}}
Meteor uses extended semver versioning for its packages: that means that the version
number has three parts separated by dots: major version, minor version and patch version
(for example: 1.2.3) with an optional pre-release version. You can read more about it on
[semver.org](http://www.semver.org).
Additionally, because some meteor packages wrap external libraries,
Meteor supports the convention of using `_` to denote a wrap number.
You can read more about [`package.js`](#packagejs) files in the API
section.
A word on testing: since testing is an important part of the development process,
there are two common ways to test a package:
* Integration tests (putting a package directly into an application, and writing
tests against the application) is the most common way to test a package. After
creating your package, add it to your app's /packages directory and run `meteor add`.
This will add your package to your app as a local package. You can then
test and run your app as usual. Meteor will detect and respond to changes to
your local package, just as it does to your app files.
* Unit tests are run with the command [`meteor test-packages package-name`](#meteortestpackages).
As described in the [`package.js`](#packagejs)
section, you can use the `package.js` file to specify where your unit tests are
located. If you have a repository that contains only the package source, you can
test your package by specifying the path to the package directory (which must
contain a slash), such as `meteor test-packages ./`.
To publish a package, run [`meteor publish`](#meteorpublish) from the package
directory. There are some extra restrictions on published packages: they must
contain a version (Meteor packages are versioned using
strict <a href="http://www.semver.org">semver</a> versioning) and their names
must be prefixed with the username of the author and a colon, like so:
`iron:router`. This namespacing allows for more descriptive and on-topic package
names.
{{/markdown}}
</template>

View File

@@ -1,37 +0,0 @@
<template name="fullApiContent">
{{> introduction }}
{{> api }}
{{> packages }}
{{> commandline }}
</template>
<template name="dtdd">
{{! can be used with either one argument (which ends up in the data
context, or with both name and type }}
{{#if name}}
<dt><span class="name" id={{#if id}}{{id}}{{/if}}>{{{name}}}</span>
{{#if type}}<span class="type">{{type}}</span>{{/if}}
</dt>
{{else}}
<dt><span class="name">{{{.}}}</span></dt>
{{/if}}
<dd>{{#markdown}}{{> UI.contentBlock}}{{/markdown}}</dd>
</template>
<!-- this is used within {{#markdown}}. <div> must be unindented.
http://daringfireball.net/projects/markdown/syntax#html -->
<template name="warning">
<div class="warning">
{{#markdown}}{{> UI.contentBlock}}{{/markdown}}
</div>
</template>
<!-- this is used within {{#markdown}}. <div> must be unindented.
http://daringfireball.net/projects/markdown/syntax#html -->
<template name="note">
<div class="note">
{{#markdown}}{{> UI.contentBlock}}{{/markdown}}
</div>
</template>

View File

@@ -1,73 +0,0 @@
check_links = function() {
var body = document.body.innerHTML;
var id_set = {};
body.replace(/id\s*=\s*"(.*?)"/g, function(match, id) {
if (! id) return;
if (id_set['$'+id]) {
console.log("ERROR: Duplicate id: "+id);
} else {
id_set['$'+id] = true;
}
});
body.replace(/"#(.*?)"/g, function(match, frag) {
if (! frag) return;
if (! id_set['$'+frag]) {
var suggestions = [];
_.each(_.keys(id_set), function(id) {
id = id.slice(1);
if (id.slice(-frag.length) === frag ||
frag.slice(-id.length) === id) {
suggestions.push(id);
}
});
var msg = "ERROR: id not found: "+frag;
if (suggestions.length > 0) {
msg += " -- suggest "+suggestions.join(', ');
}
console.log(msg);
}
});
return "DONE";
};
var basicTypes = ["String", "Number", "Boolean", "Function", "Any", "Object",
"Array", "null", "undefined", "Integer", "Error"];
// are all types either normal types or links?
check_types = function () {
$(".new-api-box .type").each(function () {
var typeSpan = this;
var typesPipeSeparated =
$(typeSpan).text().replace(/, or /g, "|").replace(/( or )/g, "|")
.replace(/, /g, "|");
_.each(typesPipeSeparated.split("|"), function (text) {
if (! text) {
console.log(typeSpan);
return;
}
text = text.replace(/^\s+|\s+$/g, '');
if (_.contains(basicTypes, text)) {
return; // all good
}
var hasLink = false;
$(typeSpan).find("a").each(function () {
if ($(this).text().replace(/^\s+|\s+$/g, '') === text) {
hasLink = true;
}
});
if (! hasLink) {
console.log("No link for: " + text);
}
});
});
};

View File

@@ -1,14 +0,0 @@
<template name="introduction">
<div id="introduction">
<!-- clicking this anchor in the left bar should scroll to top of doc,
not here -->
{{#markdown}}
<h1 id="meteorguide">Meteor Guide</h1>
The best point to get started with Meteor is the [Meteor Guide](http://guide.meteor.com). From there you can find links to other resources, intructions to install Meteor, and associated content. This is the Meteor API docs, documenting the interface of Meteor's core APIs.
{{/markdown}}
</div>
</template>

View File

@@ -1,183 +0,0 @@
// get the docs id from the name
nameToId = {
"Meteor.isClient": "meteor_isclient",
"Meteor.isServer": "meteor_isserver",
"Meteor.startup": "meteor_startup",
"Meteor.users": "meteor_users",
"Tracker.autorun": "tracker_autorun",
"Mongo.Collection#find": "find",
"Meteor.status": "meteor_status",
"Meteor.user": "meteor_user",
"Meteor.userId": "meteor_userid",
"Meteor.loggingIn": "meteor_loggingin",
"Mongo.Cursor#observe": "observe",
"Mongo.Cursor#observeChanges": "observe_changes",
"Subscription#added": "publish_added",
"Subscription#changed": "publish_changed",
"Subscription#removed": "publish_removed",
"Subscription#ready": "publish_ready",
"Meteor.Error": "meteor_error",
"Meteor.onConnection": "meteor_onconnection",
"Mongo.Collection": "mongo_collection",
"Mongo.Collection#insert": "insert",
"Mongo.Collection#update": "update",
"Mongo.Collection#remove": "remove",
"Meteor.reconnect": "meteor_reconnect",
"Meteor.methods": "meteor_methods",
"Meteor.disconnect": "meteor_disconnect",
"DDP.connect": "ddp_connect",
"Mongo.ObjectID": "mongo_object_id",
"Mongo.Collection#allow": "allow",
"Meteor.publish": "meteor_publish",
"Mongo.Collection#deny": "deny",
"Mongo.Collection#upsert": "upsert",
"Mongo.Cursor#forEach": "foreach",
"Mongo.Cursor#map": "map",
"Mongo.Cursor#fetch": "fetch",
"EJSON.equals": "ejson_equals",
"Mongo.Collection#findOne": "findone",
"Session.get": "session_get",
"Session.set": "session_set",
"Subscription#userId": "publish_userId",
"DDPCommon.MethodInvocation#userId": "method_userId",
"AccountsClient": "accountsclient",
"AccountsServer": "accountsserver",
"Accounts.verifyEmail": "accounts_verifyemail",
"Accounts.forgotPassword": "accounts_forgotpassword",
"Accounts.createUser": "accounts_createuser",
"AccountsCommon#userId": "accounts_userid",
"AccountsCommon#user": "accounts_user",
"AccountsCommon#config": "accounts_config",
"AccountsCommon#onLogin": "accounts_onlogin",
"AccountsCommon#onLoginFailure": "accounts_onloginfailure",
"AccountsClient#loggingIn": "accounts_loggingin",
"AccountsServer#validateLoginAttempt": "accounts_validateloginattempt",
"AccountsServer#validateNewUser": "accounts_validatenewuser",
"Accounts.setPassword": "accounts_setpassword",
"Accounts.sendEnrollmentEmail": "accounts_sendenrollmentemail",
"AccountsServer#onCreateUser": "accounts_oncreateuser",
"Accounts.sendResetPasswordEmail": "accounts_sendresetpasswordemail",
"Accounts.resetPassword": "accounts_resetpassword",
"Accounts.sendVerificationEmail": "accounts_sendverificationemail",
"Accounts.emailTemplates": "accounts_emailtemplates",
"Accounts.onResetPasswordLink": "Accounts-onResetPasswordLink",
"Accounts.onEnrollmentLink": "Accounts-onEnrollmentLink",
"Accounts.onEmailVerificationLink": "Accounts-onEmailVerificationLink",
"Tracker.flush": "tracker_flush",
"Tracker.afterFlush": "tracker_afterflush",
"Tracker.active": "tracker_active",
"Tracker.Dependency#depend": "dependency_depend",
"Tracker.onInvalidate": "tracker_oninvalidate",
"Tracker.Computation#onInvalidate": "computation_oninvalidate",
"Tracker.Computation#onStop": "computation_onstop",
"Tracker.Computation#stop": "computation_stop",
"Tracker.currentComputation": "tracker_currentcomputation",
"Session.equals": "session_equals",
"EJSON.newBinary": "ejson_new_binary",
"EJSON.addType": "ejson_add_type",
"DDPCommon.MethodInvocation#unblock": "method_unblock",
"Accounts.ui.config": "accounts_ui_config",
"Meteor.settings": "meteor_settings",
"undefined": "meteorpublishforarch",
"Meteor.wrapAsync": "meteor_wrapasync",
"Meteor.absoluteUrl": "meteor_absoluteurl",
"Meteor.release": "meteor_release",
"Subscription#onStop": "publish_onstop",
"Subscription#error": "publish_error",
"Subscription#stop": "publish_stop",
"Subscription#connection": "publish_connection",
"DDPCommon.MethodInvocation#setUserId": "method_setUserId",
"DDPCommon.MethodInvocation#isSimulation": "method_issimulation",
"DDPCommon.MethodInvocation#connection": "method_connection",
"Mongo.Cursor#count": "count",
"Session.setDefault": "session_set_default",
"AccountsClient#logout": "accounts_logout",
"AccountsClient#logoutOtherClients": "accounts_logoutotherclients",
"Meteor.logout": "meteor_logout",
"Meteor.logoutOtherClients": "meteor_logoutotherclients",
"Meteor.loginWithPassword": "meteor_loginwithpassword",
"Accounts.changePassword": "accounts_changepassword",
"Meteor.setTimeout": "meteor_settimeout",
"Meteor.setInterval": "meteor_setinterval",
"Meteor.clearTimeout": "meteor_cleartimeout",
"Meteor.clearInterval": "meteor_clearinterval",
"Tracker.nonreactive": "tracker_nonreactive",
"Tracker.Computation#invalidate": "computation_invalidate",
"Tracker.Computation#stopped": "computation_stopped",
"Tracker.Computation#invalidated": "computation_invalidated",
"Tracker.Computation#firstRun": "computation_firstrun",
"Tracker.Dependency#changed": "dependency_changed",
"Tracker.Dependency#hasDependents": "dependency_hasdependents",
"EJSON.parse": "ejson_parse",
"EJSON.stringify": "ejson_stringify",
"EJSON.fromJSONValue": "ejson_from_json_value",
"EJSON.toJSONValue": "ejson_to_json_value",
"EJSON.clone": "ejson_clone",
"EJSON.isBinary": "ejson_is_binary",
"HTTP.call": "http_call",
"Meteor.isCordova": "meteor_iscordova",
"Template#events": "template_events",
"Template#helpers": "template_helpers",
"Template#rendered": "template_rendered",
"Template#created": "template_created",
"Template#destroyed": "template_destroyed",
"Template#onRendered": "template_onRendered",
"Template#onCreated": "template_onCreated",
"Template#onDestroyed": "template_onDestroyed",
"Blaze.TemplateInstance#findAll": "template_findAll",
"Blaze.TemplateInstance#$": "template_$",
"Blaze.TemplateInstance#find": "template_find",
"Blaze.TemplateInstance#firstNode": "template_firstNode",
"Blaze.TemplateInstance#lastNode": "template_lastNode",
"Blaze.TemplateInstance#data": "template_data",
"Blaze.TemplateInstance#autorun": "template_autorun",
"Blaze.TemplateInstance#view": "template_view",
"Template.registerHelper": "template_registerhelper",
"Template.instance": "template_instance",
"Template.currentData": "template_currentdata",
"Template.parentData": "template_parentdata",
"Template.body": "template_body",
"ReactiveVar": "reactivevar",
"ReactiveVar#get": "reactivevar_get",
"ReactiveVar#set": "reactivevar_set",
"HTTP.get": "http_get",
"HTTP.post": "http_post",
"HTTP.put": "http_put",
"HTTP.del": "http_del",
"Email.send": "email_send",
"Assets.getText": "assets_getText",
"Assets.getBinary": "assets_getBinary",
"Blaze.render": "blaze_render",
"Blaze.renderWithData": "blaze_renderwithdata",
"Blaze.View": "blaze_view",
"Blaze.remove": "blaze_remove",
"Blaze.getData": "blaze_getdata",
"Blaze.toHTML": "blaze_tohtml",
"Blaze.toHTMLWithData": "blaze_tohtmlwithdata",
"Blaze.currentView": "blaze_currentview",
"Blaze.getView": "blaze_getview",
"Blaze.With": "blaze_with",
"Blaze.If": "blaze_if",
"Blaze.Unless": "blaze_unless",
"Blaze.Each": "blaze_each",
"Blaze.Template": "blaze_template",
"Blaze.isTemplate": "blaze_istemplate",
"Meteor.subscribe": "meteor_subscribe",
"Meteor.call": "meteor_call",
"Meteor.apply": "meteor_apply",
"PackageAPI#versionsFrom": "pack_versions",
"PackageAPI#imply": "pack_api_imply",
"PackageAPI#export": "pack_export",
"PackageAPI#addFiles": "pack_addFiles",
"PackageAPI#use": "pack_use",
"Package.onUse": "pack_onUse",
"Meteor.loginWith<ExternalService>": "meteor_loginwithexternalservice",
"EJSON.CustomType#typeName": "ejson_type_typeName",
"EJSON.CustomType#toJSONValue": "ejson_type_toJSONValue",
"EJSON.CustomType#clone": "ejson_type_clone",
"EJSON.CustomType#equals": "ejson_type_equals",
"Match.test": "match_test",
"Template.dynamic": "template_dynamic",
"currentUser": "template_currentuser",
"loggingIn": "template_loggingin"
};

View File

@@ -1,40 +0,0 @@
<template name="packages">
{{#markdown}}
<h1 id="packages">Packages</h1>
Meteor supports a variety of add-on packages and third party
libraries. While you can build great applications using only the Meteor
core functionality, optional packages can make development even faster
and better.
Packages can be added to a Meteor project with:
```bash
meteor add <package_name>
```
and removed with:
```bash
meteor remove <package_name>
```
Some of the packages that Meteor Development Group maintains include:
{{> pkg_appcache}}
{{> pkg_accounts_ui}}
{{> pkg_audit_argument_checks}}
{{> pkg_coffeescript}}
{{> pkg_ecmascript}}
{{> pkg_jquery}}
{{> pkg_less}}
{{> pkg_markdown}}
{{> pkg_modules}}
{{> pkg_oauth_encryption}}
{{> pkg_random}}
{{> pkg_spacebars}}
{{> pkg_underscore}}
{{> pkg_webapp}}
{{/markdown}}
</template>

View File

@@ -1,31 +0,0 @@
{{#template name="pkg_accounts_ui"}}
## `accounts-ui`
A turn-key user interface for Meteor Accounts.
To add Accounts and a set of login controls to an application, add the
`accounts-ui` package and at least one login provider package:
`accounts-password`, `accounts-facebook`, `accounts-github`,
`accounts-google`, `accounts-twitter`, or `accounts-weibo`.
Then simply add the `{{dstache}}> loginButtons}}` helper to an HTML file. This
will place a login widget on the page. If there is only one provider configured
and it is an external service, this will add a login/logout button. If you use
`accounts-password` or use multiple external login services, this will add
a "Sign in" link which opens a dropdown menu with login options. If you plan to
position the login dropdown in the right edge of the screen, use
`{{dstache}}> loginButtons align="right"}}` in order to get the dropdown to lay
itself out without expanding off the edge of the screen.
To configure the behavior of `{{dstache}}> loginButtons}}`, use
[`Accounts.ui.config`](#accounts_ui_config).
`accounts-ui` also includes modal popup dialogs to handle links from
[`sendResetPasswordEmail`](#accounts_sendresetpasswordemail), [`sendVerificationEmail`](#accounts_sendverificationemail),
and [`sendEnrollmentEmail`](#accounts_sendenrollmentemail). These
do not have to be manually placed in HTML: they are automatically activated
when the URLs are loaded.
If you want to control the look and feel of your accounts system a little more, we recommend reading the [useraccounts](http://guide.meteor.com/accounts.html#useraccounts) section of the Meteor Guide.
{{/template}}

View File

@@ -1,82 +0,0 @@
{{#template name="pkg_appcache"}}
## `appcache`
The `appcache` package stores the static parts of a Meteor application
(the client side Javascript, HTML, CSS, and images) in the browser's
[application cache](https://en.wikipedia.org/wiki/AppCache). To enable
caching simply add the `appcache` package to your project.
* Once a user has visited a Meteor application for the first time and
the application has been cached, on subsequent visits the web page
loads faster because the browser can load the application out of the
cache without contacting the server first.
* Hot code pushes are loaded by the browser in the background while the
app continues to run. Once the new code has been fully loaded the
browser is able to switch over to the new code quickly.
* The application cache allows the application to be loaded even when
the browser doesn't have an Internet connection, and so enables using
the app offline.
(Note however that the `appcache` package by itself doesn't make
*data* available offline: in an application loaded offline, a Meteor
Collection will appear to be empty in the client until the Internet
becomes available and the browser is able to establish a DDP
connection).
To turn AppCache off for specific browsers use:
Meteor.AppCache.config({
chrome: false,
firefox: false
});
The supported browsers that can be enabled or disabled include, but are
not limited to, `android`, `chrome`, `chromium`, `chromeMobileIOS`,
`firefox`, `ie`, `mobileSafari` and `safari`.
Browsers limit the amount of data they will put in the application
cache, which can vary due to factors such as how much disk space is
free. Unfortunately if your application goes over the limit rather
than disabling the application cache altogether and running the
application online, the browser will instead fail that particular
*update* of the cache, leaving your users running old code.
Thus it's best to keep the size of the cache below 5MB. The
`appcache` package will print a warning on the Meteor server console
if the total size of the resources being cached is over 5MB.
If you have files too large to fit in the cache you can disable
caching by URL prefix. For example,
Meteor.AppCache.config({onlineOnly: ['/online/']});
causes files in your `public/online` directory to not be cached, and
so they will only be available online. You can then move your large
files into that directory and refer to them at the new URL:
<img src="/online/bigimage.jpg">
If you'd prefer not to move your files, you can use the file names
themselves as the URL prefix:
Meteor.AppCache.config({
onlineOnly: [
'/bigimage.jpg',
'/largedata.json'
]
});
though keep in mind that since the exclusion is by prefix (this is a
limitation of the application cache manifest), excluding
`/largedata.json` will also exclude such URLs as
`/largedata.json.orig` and `/largedata.json/file1`.
For more information about how Meteor interacts with the application
cache, see the
[AppCache page](https://github.com/meteor/meteor/wiki/AppCache)
in the Meteor wiki.
{{/template}}

View File

@@ -1,16 +0,0 @@
{{#template name="pkg_audit_argument_checks"}}
## `audit-argument-checks`
This package causes Meteor to require that all arguments passed to methods and
publish functions are [`check`ed](#check). Any method that does not pass each
one of its arguments to `check` will throw an error, which will be logged on the
server and which will appear to the client as a
`500 Internal server error`. This is a simple way to help ensure that your
app has complete check coverage.
Methods and publish functions that do not need to validate their arguments can
simply run `check(arguments, [Match.Any])` to satisfy the
`audit-argument-checks` coverage checker.
{{/template}}

View File

@@ -1,50 +0,0 @@
{{#template name="pkg_coffeescript"}}
## `coffeescript`
[CoffeeScript](http://coffeescript.org/) is a little language that
compiles into JavaScript. It provides a simple syntax without lots of
braces and parentheses. The code compiles one-to-one into the
equivalent JS, and there is no interpretation at runtime.
CoffeeScript is supported on both the client and the server. Files
ending with `.coffee`, `.litcoffee`, or `.coffee.md` are automatically
compiled to JavaScript.
### Namespacing and CoffeeScript
Here's how CoffeeScript works with Meteor's namespacing.
* Per the usual CoffeeScript convention, CoffeeScript variables are
file-scoped by default (visible only in the `.coffee` file where
they are defined.)
* When writing a package, CoffeeScript-defined variables can be
exported like any other variable (see [Writing
Packages](#writingpackages)). Exporting a variable pulls it up to
package scope, meaning that it will be visible to all of the code in
your app or package (both `.js` and `.coffee` files).
* Package-scope variables declared in `.js` files are visible in any
`.coffee` files in the same app or project.
* There is no way to make a package-scope variable from a `.coffee`
file other than exporting it. We couldn't figure out a way to make
this fit naturally inside the CoffeeScript language. If you want to
use package-scope variables with CoffeeScript, one way is to make a
short `.js` file that declares all of your package-scope
variables. They can then be used and assigned to from `.coffee`
files.
* If you want to share variables between `.coffee` files in the same
package, and don't want to separately declare them in a `.js` file,
we have an experimental feature that you may like. An object called
`share` is visible in CoffeeScript code and is shared across all
`.coffee` files in the same package. So, you can write `share.foo`
for a value that is shared between all CoffeeScript code in a
package, but doesn't escape that package.
Heavy CoffeeScript users, please let us know how this arrangement
works for you, whether `share` is helpful for you, and anything else
you'd like to see changed.
{{/template}}

View File

@@ -1,313 +0,0 @@
{{#template name="pkg_ecmascript"}}
## `ecmascript`
This package lets you use new JavaScript language features that are part
of the [ECMAScript 2015
specification](http://www.ecma-international.org/ecma-262/6.0/) but are
not yet supported by all engines or browsers. Unsupported syntax is
automatically translated into standard JavaScript that behaves the same
way.
[This video](https://www.youtube.com/watch?v=05Z6YGiZKmE) from the July
2015 Meteor Devshop gives an overview of how the package works, and what
it provides.
### Usage
The `ecmascript` package registers a compiler plugin that transpiles
ECMAScript 2015+ to ECMAScript 5 (standard JS) in all `.js` files. By
default, this package is pre-installed for all new apps and packages.
To add this package to an existing app, run the following command from
your app directory:
```bash
meteor add ecmascript
```
To add the `ecmascript` package to an existing package, include the
statement `api.use('ecmascript');` in the `Package.onUse` callback in your
`package.js` file:
```js
Package.onUse(function (api) {
api.use('ecmascript');
});
```
### Supported ES2015 Features
#### Syntax
The `ecmascript` package uses [Babel](http://babeljs.io/) to compile
ES2015 syntax to ES5 syntax. Many but not all ES2015 features can be
simulated by Babel, and `ecmascript` enables most of the features
supported by Babel.
Here is a list of the Babel transformers that are currently enabled:
* [`es3.propertyLiterals`](https://babeljs.io/docs/advanced/transformers/es3/property-literals/)<br>
Makes it safe to use reserved keywords like `catch` as unquoted keys in
object literals. For example, `{ catch: 123 }` is translated to `{ "catch": 123 }`.
* [`es3.memberExpressionLiterals`](https://babeljs.io/docs/advanced/transformers/es3/member-expression-literals/)<br>
Makes it safe to use reserved keywords as property names. For
example, `object.catch` is translated to `object["catch"]`.
* [`es6.arrowFunctions`](http://babeljs.io/docs/learn-es2015/#arrows)<br>
Provides a shorthand for function expressions. For example,
`[1, 2, 3].map(x => x + 1)` evaluates to `[2, 3, 4]`. If `this` is used
in the body of the arrow function, it will be automatically bound to the
value of `this` in the enclosing scope.
* [`es6.literals`](http://babeljs.io/docs/learn-es2015/#binary-and-octal-literals)<br>
Adds support for binary and octal numeric literals. For example,
`0b111110111 === 503` and `0o767 === 503`.
* [`es6.templateLiterals`](http://babeljs.io/docs/learn-es2015/#template-strings)<br>
Enables multi-line strings delimited by backticks instead of quotation
marks, with variable interpolation:
```js
var name = "Ben";
var message = `My name is:
${name}`;
```
* [`es6.classes`](http://babeljs.io/docs/learn-es2015/#classes)<br>
Enables `class` syntax:
```js
class Base {
constructor(a, b) {
this.value = a * b;
}
}
class Derived extends Base {
constructor(a, b) {
super(a + 1, b + 1);
}
}
var d = new Derived(2, 3);
d.value; // 12
```
* [`es6.constants`](https://babeljs.io/docs/learn-es2015/#let-const)<br>
Allows defining block-scoped variables that are not allowed to be
redefined:
```js
const GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
// This reassignment will be forbidden by the compiler:
GOLDEN_RATIO = "new value";
```
* [`es6.blockScoping`](http://babeljs.io/docs/learn-es2015/#let-const)<br>
Enables the `let` and `const` keywords as alternatives to `var`. The key
difference is that variables defined using `let` or `const` are
visible only within the block where they are declared, rather than being
visible anywhere in the enclosing function. For example:
```js
function example(condition) {
let x = 0;
if (condition) {
let x = 1;
console.log(x);
} else {
console.log(x);
x = 2;
}
return x;
}
example(true); // logs 1, returns 0
example(false); // logs 0, returns 2
```
* [`es6.properties.shorthand`](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)<br>
Allows omitting the value of an object literal property when the desired
value is held by a variable that has the same name as the property
key. For example, instead of writing `{ x: x, y: y, z: "asdf" }` you can
just write `{ x, y, z: "asdf" }`. Methods can also be written without
the `: function` property syntax:
```js
var obj = {
oldWay: function (a, b) { ... },
newWay(a, b) { ... }
};
```
* [`es6.properties.computed`](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals)<br>
Allows object literal properties with dynamically computed keys:
```js
var counter = 0;
function getKeyName() {
return "key" + counter++;
}
var obj = {
[getKeyName()]: "zero",
[getKeyName()]: "one",
};
obj.key0; // "zero"
obj.key1; // "one"
```
* [`es6.parameters`](http://babeljs.io/docs/learn-es2015/#default-rest-spread)<br>
Default expressions for function parameters, evaluated whenever the parameter
is `undefined`, `...rest` parameters for capturing remaining
arguments without using the `arguments` object:
```js
function add(a = 0, ...rest) {
rest.forEach(n => a += n);
return a;
}
add(); // 0
add(1, 2, 3); // 6
```
* [`es6.spread`](http://babeljs.io/docs/learn-es2015/#default-rest-spread)<br>
Allows an array of arguments to be interpolated into a list of arguments
to a function call, `new` expression, or array literal, without using
`Function.prototype.apply`:
```js
add(1, ...[2, 3, 4], 5); // 15
new Node("name", ...children);
[1, ...[2, 3, 4], 5]; // [1, 2, 3, 4, 5]
```
* [`es6.forOf`](http://babeljs.io/docs/learn-es2015/#iterators-for-of)<br>
Provides an easy way to iterate over the elements of a collection:
```js
let sum = 0;
for (var x of [1, 2, 3]) {
sum += x;
}
x; // 6
```
* [`es6.destructuring`](http://babeljs.io/docs/learn-es2015/#destructuring)<br>
Destructuring is the technique of using an array or object pattern on
the left-hand side of an assignment or declaration, in place of the
usual variable or parameter, so that certain sub-properties of the value
on the right-hand side will be bound to identifiers that appear within the
pattern. Perhaps the simplest example is swapping two variables without
using a temporary variable:
```js
[a, b] = [b, a];
```
Extracting a specific property from an object:
```js
let { username: name } = user;
// is equivalent to
let name = user.username;
```
Instead of taking a single opaque `options` parameter, a function can
use an object destructuring pattern to name the expected options:
```js
function run({ command, args, callback }) { ... }
run({
command: "git",
args: ["status", "."],
callback(error, status) { ... },
unused: "whatever"
});
```
* [`es7.objectRestSpread`](https://github.com/sebmarkbage/ecmascript-rest-spread)<br>
Supports catch-all `...rest` properties in object literal declarations
and assignments:
```js
let { x, y, ...rest } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
rest; // { a: 3, b: 4 }
```
Also enables `...spread` properties in object literal expressions:
```js
let n = { x, y, ...rest };
n; // { x: 1, y: 2, a: 3, b: 4 }
```
* [`es7.trailingFunctionCommas`](https://github.com/jeffmo/es-trailing-function-commas)<br>
Allows the final parameter of a function to be followed by a comma,
provided that parameter is not a `...rest` parameter.
* [`flow`](https://babeljs.io/docs/advanced/transformers/other/flow/)<br>
Permits the use of [Flow](http://flowtype.org/) type annotations. These
annotations are simply stripped from the code, so they have no effect on
the code's behavior, but you can run the `flow` tool over your code to
check the types if desired.
#### Polyfills
The ECMAScript 2015 standard library has grown to include new APIs and
data structures, some of which can be implemented ("polyfilled") using
JavaScript that runs in all engines and browsers today. Here are three new
constructors that are guaranteed to be available when the `ecmascript`
package is installed:
* [`Promise`](https://github.com/meteor/promise)<br>
A `Promise` allows its owner to wait for a value that might not be
available yet. See [this tutorial](https://www.promisejs.org/) for more
details about the API and motivation. The Meteor `Promise`
implementation is especially useful because it runs all callback
functions in recycled `Fiber`s, so you can use any Meteor API, including
those that yield (e.g. `HTTP.get`, `Meteor.call`, or `MongoCollection`),
and you never have to call `Meteor.bindEnvironment`.
* [`Map`](https://github.com/zloirock/core-js#map)<br>
An associative key-value data structure where the keys can be any
JavaScript value (not just strings). Lookup and insertion take constant
time.
* [`Set`](https://github.com/zloirock/core-js#set)<br>
A collection of unique JavaScript values of any type. Lookup and
insertion take constant time.
* [`Symbol`](https://github.com/zloirock/core-js#ecmascript-6-symbol)<br>
An implementation of the global
[`Symbol`](http://www.2ality.com/2014/12/es6-symbols.html)s namespace
that enables a number of other ES2015 features, such as `for`-`of` loops
and `Symbol.iterator` methods: `[1,2,3][Symbol.iterator]()`.
* Polyfills for the following [`Object`](https://github.com/zloirock/core-js#ecmascript-6-object)-related methods:
* `Object.assign`
* `Object.is`
* `Object.setPrototypeOf`
* `Object.prototype.toString` (fixes `@@toStringTag` support)<br>
Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).
* Polyfills for the following [`String`](https://github.com/zloirock/core-js#ecmascript-6-string)-related methods:
* `String.fromCodePoint`
* `String.raw`
* `String.prototype.includes`
* `String.prototype.startsWith`
* `String.prototype.endsWith`
* `String.prototype.repeat`
* `String.prototype.codePointAt`
* `String.prototype.trim`<br>
Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String).
* Polyfills for the following [`Array`](https://github.com/zloirock/core-js#ecmascript-6-array)-related methods:
* `Array.from`
* `Array.of`
* `Array.prototype.copyWithin`
* `Array.prototype.fill`
* `Array.prototype.find`
* `Array.prototype.findIndex`
Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
* Polyfills for the following [`Function`](https://github.com/zloirock/core-js#ecmascript-6-function)-related properties:
* `Function.prototype.name` (fixes IE9+)
* `Function.prototype[Symbol.hasInstance]` (fixes IE9+)
Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
{{/template}}

View File

@@ -1,19 +0,0 @@
{{#template name="pkg_jquery"}}
## `jquery`
[jQuery](http://jquery.com/) is a fast and concise JavaScript
Library that simplifies HTML document traversing, event handling,
animating, and Ajax interactions for rapid web development.
The `jquery` package adds the jQuery library to the client JavaScript
bundle. It has no effect on the server.
In addition to the `jquery` package, Meteor provides several jQuery
plugins as separate packages. These include:
* [`jquery-history`](https://github.com/balupton/history.js)
* [`jquery-layout`](http://layout.jquery-dev.net/)
* [`jquery-waypoints`](http://imakewebthings.com/jquery-waypoints/)
{{/template}}

View File

@@ -1,17 +0,0 @@
{{#template name="pkg_less"}}
## `less`
[LESS](http://lesscss.org/) extends CSS with dynamic behavior such as variables, mixins,
operations and functions. It allows for more compact stylesheets and
helps reduce code duplication in CSS files.
With the `less` package installed, `.less` files in your application are
automatically compiled to CSS and the results are included in the client CSS
bundle.
{{#note}}
If you want to `@import` a file, give it the extension `.import.less`
to prevent Meteor from processing it independently.
{{/note}}
{{/template}}

View File

@@ -1,19 +0,0 @@
{{#template name="pkg_markdown"}}
## `markdown`
This package lets you use Markdown in your templates. It's easy: just
put your markdown inside `{{dstache}}#markdown}} ... {{dstache}}/markdown}}`
tags. You can still use all of the usual Meteor template features
inside a Markdown block, such as `{{dstache}}#each}}`, and you still get
reactivity.
Example:
`{{dstache}}#markdown}}I am using __markdown__.{{dstache}}/markdown}}`
outputs
<p>I am using <strong>markdown</strong>.</p>
{{/template}}

View File

@@ -1,199 +0,0 @@
{{#template name="pkg_modules"}}
## `modules`
Though Meteor 1.2 introduced support for [many new ECMAScript 2015 features](https://github.com/meteor/meteor/blob/devel/packages/ecmascript/README.md#supported-es2015-features), one of the most notable omissions was [ES2015 `import` and `export` syntax](http://exploringjs.com/es6/ch_modules.html). Meteor 1.3 fills that gap with a fully standards-compliant module system that works on both the client and the server, solves multiple long-standing problems for Meteor applications (such as controlling file load order), and yet maintains full backwards compatibility with existing Meteor code. This document explains the usage and key features of the new module system.
### Enabling modules
We think youre going to love the new module system, and that's why it will be installed by default for all new apps and packages. Nevertheless, the `modules` package is totally optional, and it will be up to you to add it to existing apps and/or packages.
For apps, this is as easy as `meteor add modules`, or (even better) `meteor add ecmascript`, since the `ecmascript` package *implies* the `modules` package.
For packages, you can enable `modules` by adding `api.use("modules")` to the `Package.onUse` or `Package.onTest` sections of your `package.js` file.
Now, you might be wondering what good the `modules` package is without the `ecmascript` package, since `ecmascript` enables `import` and `export` syntax. By itself, the `modules` package provides the CommonJS `require` and `exports` primitives that may be familiar if youve ever written Node code, and the `ecmascript` package simply compiles `import` and `export` statements to CommonJS. The `require` and `export` primitives also allow Node modules to run within Meteor application code without modification. Furthermore, keeping `modules` separate allows us to use `require` and `exports` in places where using `ecmascript` is tricky, such as the implementation of the `ecmascript` package itself.
While the `modules` package is useful by itself, we very much encourage using the `ecmascript` package (and thus `import` and `export`) instead of using `require` and `exports` directly. If you need convincing, heres a presentation that explains the differences: http://benjamn.github.io/empirenode-2015
### Basic syntax
Although there are a number of different variations of `import` and `export` syntax, this section describes the essential forms that everyone should know.
First, you can `export` any named declaration on the same line where it was declared:
```js
// exporter.js
export var a = ...;
export let b = ...;
export const c = ...;
export function d() {...}
export function* e() {...}
export class F {...}
```
These declarations make the variables `a`, `b`, `c` (and so on) available not only within the scope of the `exporter.js` module, but also to other modules that `import` from `exporter.js`.
If you prefer, you can `export` variables by name, rather than prefixing their declarations with the `export` keyword:
```js
// exporter.js
function g() {...}
let h = g();
// at the end of the file
export {g, h};
```
All of these exports are *named*, which means other modules can import them using those names:
```js
// importer.js
import {a, c, F, h} from "./exporter";
new F(a, c).method(h);
```
If youd rather use different names, youll be glad to know `export` and `import` statements can rename their arguments:
```js
// exporter.js
export {g as x};
g(); // same as calling y() in importer.js
```
```js
// importer.js
import {x as y} from "./exporter";
y(); // same as calling g() in exporter.js
```
As with CommonJS `module.exports`, it is possible to define a single *default* export:
```js
// exporter.js
export default any.arbitrary(expression);
```
This default export may then be imported without curly braces, using any name the importing module chooses:
```js
// importer.js
import Value from "./exporter";
// Value is identical to the exported expression
```
Unlike CommonJS `module.exports`, the use of default exports does not prevent the simultaneous use of named exports. Here is how you can combine them:
```js
// importer.js
import Value, {a, F} from "./exporter";
```
In fact, the default export is conceptually just another named export whose name happens to be "default":
```js
// importer.js
import {default as Value, a, F} from "./exporter";
```
These examples should get you started with `import` and `export` syntax. For further reading, here is a very detailed [explanation](http://www.2ality.com/2014/09/es6-modules-final.html) by [Axel Rauschmayer](https://twitter.com/rauschma) of every variation of `import` and `export` syntax.
### Modular application structure
Before the release of Meteor 1.3, the only way to share values between files in an application was to assign them to global variables or communicate through shared variables like `Session` (variables which, while not technically global, sure do feel syntactically identical to global variables). With the introduction of modules, one module can refer precisely to the exports of any other specific module, so global variables are no longer necessary.
If you are familiar with modules in Node, you might expect modules not to be evaluated until the first time you import them. However, because earlier versions of Meteor evaluated all of your code when the application started, and we care about backwards compatibility, eager evaluation is still the default behavior.
If you would like a module to be evaluated *lazily* (in other words: on demand, the first time you import it, just like Node does it), then you should put that module in an `imports/` directory (anywhere in your app, not just the root directory), and include that directory when you import the module: `import {stuff} from "./imports/lazy"`. Note: files contained by `node_modules/` directories will also be evaluated lazily (more on that below).
Lazy evaluation will very likely become the default behavior in a future version of Meteor, but if you want to embrace it as fully as possible in the meantime, we recommend putting all your modules inside either `client/imports/` or `server/imports/` directories, with just a single entry point for each architecture: `client/main.js` and `server/main.js`. The `main.js` files will be evaluated eagerly, giving your application a chance to import modules from the `imports/` directories.
### Modular package structure
If you are a package author, in addition to putting `api.use("modules")` or `api.use("ecmascript")` in the `Package.onUse` section of your `package.js` file, you can also use a new API called `api.mainModule` to specify the main entry point for your package:
```js
Package.describe({
name: "my-modular-package"
});
Npm.depends({
moment: "2.10.6"
});
Package.onUse(function (api) {
api.use("modules");
api.mainModule("server.js", "server");
api.mainModule("client.js", "client");
api.export("Foo");
});
```
Now `server.js` and `client.js` can import other files from the package source directory, even if those files have not been added using the `api.addFiles` function.
When you use `api.mainModule`, the exports of the main module are exposed globally as `Package["my-modular-package"]`, along with any symbols exported by `api.export`, and thus become available to any code that imports the package. In other words, the main module gets to decide what value of `Foo` will be exported by `api.export`, as well as providing other properties that can be explicitly imported from the package:
```js
// In an application that uses my-modular-package:
import {Foo as ExplicitFoo, bar} from "meteor/my-modular-package";
console.log(Foo); // Auto-imported because of api.export.
console.log(ExplicitFoo); // Explicitly imported, but identical to Foo.
console.log(bar); // Exported by server.js or client.js, but not auto-imported.
```
Note that the `import` is `from "meteor/my-modular-package"`, not `from "my-modular-package"`. Meteor package identifier strings must include the prefix `meteor/...` to disambiguate them from npm packages.
Finally, since this package is using the new `modules` package, and the package `Npm.depends` on the "moment" npm package, modules within the package can `import moment from "moment"` on both the client and the server. This is great news, because previous versions of Meteor allowed npm imports only on the server, via `Npm.require`.
### Local `node_modules`
Before Meteor 1.3, the contents of `node_modules` directories in Meteor application code were completely ignored. When you enable `modules`, those useless `node_modules` directories suddenly become infinitely more useful:
```sh
meteor create modular-app
cd modular-app
mkdir node_modules
npm install moment
echo 'import moment from "moment";' >> modular-app.js
echo 'console.log(moment().calendar());' >> modular-app.js
meteor
```
When you run this app, the `moment` library will be imported on both the client and the server, and both consoles will log output similar to: `Today at 7:51 PM`. Our hope is that the possibility of installing Node modules directly within an app will reduce the need for npm wrapper packages such as https://atmospherejs.com/momentjs/moment.
A version of the `npm` command comes bundled with every Meteor installation, and (as of Meteor 1.3) it's quite easy to use: `meteor npm ...` is synonymous with `npm ...`, so `meteor npm install moment` will work in the example above. (Likewise, if you don't have a version of `node` installed, or you want to be sure you're using the exact same version of `node` that Meteor uses, `meteor node ...` is a convenient shortcut.) That said, you can use any version of `npm` that you happen to have available. Meteor's module system only cares about the files installed by `npm`, not the details of how `npm` installs those files.
### File load order
Before Meteor 1.3, the order in which application files were evaluated was dictated by a set of rules described in the [Application Structure - Default file load order](http://guide.meteor.com/structure.html#load-order) section of the Meteor Guide. These rules could become frustrating when one file depended on a variable defined by another file, particularly when the first file was evaluated after the second file.
Thanks to modules, any load-order dependency you might imagine can be resolved by adding an `import` statement. So if `a.js` loads before `b.js` because of their file names, but `a.js` needs something defined by `b.js`, then `a.js` can simply `import` that value from `b.js`:
```js
// a.js
import {bThing} from "./b";
console.log(bThing, "in a.js");
```
```js
// b.js
export var bThing = "a thing defined in b.js";
console.log(bThing, "in b.js");
```
Sometimes a module doesnt actually need to import anything from another module, but you still want to be sure the other module gets evaluated first. In such situations, you can use an even simpler `import` syntax:
```js
// c.js
import "./a";
console.log("in c.js");
```
No matter which of these modules is imported first, the order of the `console.log` calls will always be:
```js
console.log(bThing, "in b.js");
console.log(bThing, "in a.js");
console.log("in c.js");
```
{{/template}}

View File

@@ -1,81 +0,0 @@
{{#template name="pkg_oauth_encryption"}}
## `oauth-encryption`
Encrypts sensitive login secrets stored in the database such as a
login service's application secret key and users' access tokens.
### Generating a Key
The encryption key is 16 bytes, encoded in base64.
To generate a key:
$ ~/.meteor/tools/latest/bin/node -e 'console.log(require("crypto").randomBytes(16).toString("base64"))'
### Using oauth-encryption with accounts
On the server only, use the `oauthSecretKey` option to `Accounts.config`:
Accounts.config({oauthSecretKey: "onsqJ+1e4iGFlV0nhZYobg=="});
This call to `Accounts.config` should be made at load time (place at
the top level of your source file), not called from inside of a
`Meteor.startup` block.
To avoid storing the secret key in your application's source code, you
can use [`Meteor.settings`](http://docs.meteor.com/#meteor_settings):
Accounts.config({oauthSecretKey: Meteor.settings.oauthSecretKey});
### Migrating unencrypted user tokens
This example for Twitter shows how existing unencrypted user tokens
can be encrypted. The query finds user documents which have a Twitter
access token but not the `algorithm` field which is created when the
token is encrypted. The relevant fields in the service data are then
encrypted.
Meteor.users.find({ $and: [
{ 'services.twitter.accessToken': {$exists: true} },
{ 'services.twitter.accessToken.algorithm': {$exists: false} }
] }).
forEach(function (userDoc) {
var set = {};
_.each(['accessToken', 'accessTokenSecret', 'refreshToken'], function (field) {
var plaintext = userDoc.services.twitter[field];
if (!_.isString(plaintext))
return;
set['services.twitter.' + field] = OAuthEncryption.seal(
userDoc.services.twitter[field],
userDoc._id
);
});
Meteor.users.update(userDoc._id, {$set: set});
});
### Using oauth-encryption without accounts
If you're using the oauth packages directly instead of through the
Meteor accounts packages, you can load the OAuth encryption key
directly using `OAuthEncryption.loadKey`:
OAuthEncryption.loadKey("onsqJ+1e4iGFlV0nhZYobg==");
If you call `retrieveCredential` (such as
`Twitter.retrieveCredential`) as part of your process, you'll find
when using oauth-encryption that the sensitive service data fields
will be encrypted.
You can decrypt them using `OAuth.openSecrets`:
var credentials = Twitter.retrieveCredential(token);
var serviceData = OAuth.openSecrets(credentials.serviceData);
### Using oauth-encryption on Windows
This package depends on [npm-node-aes-gcm](https://github.com/meteor/meteor/tree/devel/packages/non-core/npm-node-aes-gcm), which requires you to have OpenSSL installed on your system to run. To install OpenSSL on Windows, use one of the binaries on [this page](http://slproweb.com/products/Win32OpenSSL.html). Don't forget to install the Visual Studio 2008 redistributables if you don't have them yet.
{{/template}}

View File

@@ -1,39 +0,0 @@
{{#template name="pkg_random"}}
## `random`
The `random` package provides several functions for generating random
numbers. It uses a cryptographically strong pseudorandom number generator when
possible, but falls back to a weaker random number generator when
cryptographically strong randomness is not available (on older browsers or on
servers that don't have enough entropy to seed the cryptographically strong
generator).
<dl class="callbacks">
{{#dtdd "Random.id([n])"}}
Returns a unique identifier, such as `"Jjwjg6gouWLXhMGKW"`, that is
likely to be unique in the whole world. The optional argument `n`
specifies the length of the identifier in characters and defaults to 17.
{{/dtdd}}
{{#dtdd "Random.secret([n])"}}
Returns a random string of printable characters with 6 bits of
entropy per character. The optional argument `n` specifies the length of
the secret string and defaults to 43 characters, or 256 bits of
entropy. Use `Random.secret` for security-critical secrets that are
intended for machine, rather than human, consumption.
{{/dtdd}}
{{#dtdd "Random.fraction()"}}
Returns a number between 0 and 1, like `Math.random`.
{{/dtdd}}
{{#dtdd "Random.choice(arrayOrString)"}}
Returns a random element of the given array or string.
{{/dtdd}}
{{#dtdd "Random.hexString(n)"}}
Returns a random string of `n` hexadecimal digits.
{{/dtdd}}
</dl>
{{/template}}

View File

@@ -1,582 +0,0 @@
{{#template name="pkg_spacebars"}}
<h2 id="pkg_spacebars"><code>spacebars</code></h2>
Spacebars is a Meteor template language inspired by
[Handlebars](http://handlebarsjs.com/). It shares some of the spirit and syntax
of Handlebars, but it has been tailored to produce reactive Meteor templates
when compiled.
### Getting Started
A Spacebars template consists of HTML interspersed with template tags, which are
delimited by `{{|` and `}}` (two curly braces).
```
<template name="myPage">
<h1>{{|pageTitle}}</h1>
{{|> nav}}
{{|#each posts}}
<div class="post">
<h3>{{|title}}</h3>
<div class="post-content">
{{|{content}}}
</div>
</div>
{{|/each}}
</template>
```
As illustrated by the above example, there are four major types of template
tags:
* `{{|pageTitle}}` - Double-braced template tags are used to insert a string of
text. The text is automatically made safe. It may contain any characters
(like `<`) and will never produce HTML tags.
* `{{|> nav}}` - Inclusion template tags are used to insert another template by
name.
* `{{|#each}}` - Block template tags are notable for having a block of content.
The block tags `#if`, `#each`, `#with`, and `#unless` are built in, and it is
also possible define custom ones. Some block tags, like `#each` and `#with`,
establish a new data context for evaluating their contents. In the above
example, `{{|title}}` and `{{|content}}` most likely refer to properties of the
current post (though they could also refer to template helpers).
* `{{|{content}}}` - Triple-braced template tags are used to insert raw HTML. Be
careful with these! It's your job to make sure the HTML is safe, either by
generating it yourself or sanitizing it if it came from a user input.
### Reactivity Model
Spacebars templates update reactively at a fine-grained level in response to
changing data.
Each template tag's DOM is updated automatically when it evaluates to a new
value, while avoiding unnecessary re-rendering as much as possible. For
example, a double-braced tag replace its text node when its text value changes.
An `#if` re-renders its contents only when the condition changes from truthy to
falsy or vice versa.
### Identifiers and Paths
A Spacebars identifier is either a JavaScript identifier name or any string
enclosed in square brackets (`[` and `]`). There are also the special
identifiers `this` (or equivalently, `.`) and `..`. Brackets are required to
use one of the following as the first element of a path: `else`, `this`, `true`,
`false`, and `null`. Brackets are not required around JavaScript keywords and
reserved words like `var` and `for`.
A Spacebars path is a series of one or more identifiers separated by either `.`
or `/`, such as `foo`, `foo.bar`, `this.name`, `../title`, or `foo.[0]` (numeric indices must be enclosed in brackets).
#### Name Resolution
The first identifier in a path is resolved in one of two ways:
* Indexing the current data context. The identifier `foo` refers to the `foo`
property of the current data context object.
* As a template helper. The identifier `foo` refers to a helper function (or
constant value) that is accessible from the current template.
Template helpers take priority over properties of the data context.
If a path starts with `..`, then the *enclosing* data context is used instead of
the current one. The enclosing data context might be the one outside the
current `#each`, `#with`, or template inclusion.
#### Path Evaluation
When evaluating a path, identifiers after the first are used to index into the
object so far, like JavaScript's `.`. However, an error is never thrown when
trying to index into a non-object or an undefined value.
In addition, Spacebars will call functions for you, so `{{|foo.bar}}` may be
taken to mean `foo().bar`, `foo.bar()`, or `foo().bar()` as appropriate.
### Helper Arguments
An argument to a helper can be any path or identifier, or a string, boolean, or
number literal, or null.
Double-braced and triple-braced template tags take any number of positional and
keyword arguments:
```
{{|frob a b c verily=true}}
```
calls:
```javascript
frob(a, b, c, Spacebars.kw({verily: true}))
```
`Spacebars.kw` constructs an object that is `instanceof Spacebars.kw` and whose
`.hash` property is equal to its argument.
The helper's implementation can access the current data context as `this`.
### Inclusion and Block Arguments
Inclusion tags (`{{|> foo}}`) and block tags (`{{|#foo}}`) take a single
data argument, or no argument. Any other form of arguments will be interpreted
as an *object specification* or a *nested helper*:
* **Object specification**: If there are only keyword arguments, as in `{{|#with
x=1 y=2}}` or `{{|> prettyBox color=red}}`, the keyword arguments will be
assembled into a data object with properties named after the keywords.
* **Nested Helper**: If there is a positional argument followed by other
(positional or keyword arguments), the first argument is called on the others
using the normal helper argument calling convention.
### Template Tag Placement Limitations
Unlike purely string-based template systems, Spacebars is HTML-aware and
designed to update the DOM automatically. As a result, you can't use a template
tag to insert strings of HTML that don't stand on their own, such as a lone HTML
start tag or end tag, or that can't be easily modified, such as the name of an
HTML element.
There are three main locations in the HTML where template tags are allowed:
* At element level (i.e. anywhere an HTML tag could go)
* In an attribute value
* In a start tag in place of an attribute name/value pair
The behavior of a template tag is affected by where it is located in the HTML,
and not all tags are allowed at all locations.
## Double-braced Tags
A double-braced tag at element level or in an attribute value typically evalutes
to a string. If it evalutes to something else, the value will be cast to a
string, unless the value is `null`, `undefined`, or `false`, which results in
nothing being displayed.
Values returned from helpers must be pure text, not HTML. (That is, strings
should have `<`, not `&lt;`.) Spacebars will perform any necessary escaping if
a template is rendered to HTML.
#### SafeString
If a double-braced tag at element level evalutes to an object created with
`Spacebars.SafeString("<span>Some HTML</span>")`, the HTML is inserted at the
current location. The code that calls `SafeString` is asserting that this HTML
is safe to insert.
### In Attribute Values
A double-braced tag may be part of, or all of, an HTML attribute value:
```
<input type="checkbox" class="checky {{|moreClasses}}" checked={{|isChecked}}>
```
An attribute value that consists entirely of template tags that return `null`,
`undefined`, or `false` is considered absent; otherwise, the attribute is
considered present, even if its value is empty.
#### Dynamic Attributes
A double-braced tag can be used in an HTML start tag to specify an arbitrary set
of attributes:
```
<div {{|attrs}}>...</div>
<input type=checkbox {{|isChecked}}>
```
The tag must evaluate to an object that serves as a dictionary of attribute name
and value strings. For convenience, the value may also be a string or null. An
empty string or null expands to `{}`. A non-empty string must be an attribute
name, and expands to an attribute with an empty value; for example, `"checked"`
expands to `{checked: ""}` (which, as far as HTML is concerned, means the
checkbox is checked).
To summarize:
<table>
<thead>
<tr><th>Return Value</th><th>Equivalent HTML</th></tr>
</thead>
<tbody>
<tr><td><code>""</code> or <code>null</code> or <code>{}</code></td></tr>
<tr><td><code>"checked"</code> or <code>{checked: ""}</code></td><td><code>checked</code></td></tr>
<tr><td><code>{checked: "", 'class': "foo"}</code></td><td><code>checked class=foo</code></td></tr>
<tr><td><code>"checked class=foo"</code></td><td>ERROR, string is not an attribute name</td></tr>
</tbody>
</table>
You can combine multiple dynamic attributes tags with other attributes:
```
<div id=foo class={{|myClass}} {{|attrs1}} {{|attrs2}}>...</div>
```
Attributes from dynamic attribute tags are combined from left to right, after
normal attributes, with later attribute values overwriting previous ones.
Multiple values for the same attribute are not merged in any way, so if `attrs1`
specifies a value for the `class` attribute, it will overwrite `{{|myClass}}`.
As always, Spacebars takes care of recalculating the element's attributes if any
of `myClass`, `attrs1`, or `attrs2` changes reactively.
### Triple-braced Tags
Triple-braced tags are used to insert raw HTML into a template:
```
<div class="snippet">
{{|{snippetBody}}}
</div>
```
The inserted HTML must consist of balanced HTML tags. You can't, for example,
insert `"</div><div>"` to close an existing div and open a new one.
This template tag cannot be used in attributes or in an HTML start tag.
### Inclusion Tags
An inclusion tag takes the form `{{|> templateName}}` or `{{|> templateName
dataObj}}`. Other argument forms are syntactic sugar for constructing a data
object (see Inclusion and Block Arguments).
An inclusion tag inserts an instantiation of the given template at the current
location. If there is an argument, it becomes the data context, much as if the
following code were used:
```
{{|#with dataObj}}
{{|> templateName}}
{{|/with}}
```
Instead of simply naming a template, an inclusion tag can also specify a path
that evalutes to a template object, or to a function that returns a template
object.
Note that the above two points interact in a way that can be surprising!
If `foo` is a template helper function that returns another template, then
`{{|>foo bar}}` will _first_ push `bar` onto the data context stack _then_ call
`foo()`, due to the way this line is expanded as shown above. You will need to
use `Template.parentData(1)` to access the original context. This differs
from regular helper calls like `{{|foo bar}}`, in which `bar` is passed as a
parameter rather than pushed onto the data context stack.
### Function Returning a Template
If an inclusion tag resolves to a function, the function must return a template
object or `null`. The function is reactively re-run, and if its return value
changes, the template will be replaced.
### Block Tags
Block tags invoke built-in directives or custom block helpers, passing a block
of template content that may be instantiated once, more than once, or not at all
by the directive or helper.
```
{{|#block}}
<p>Hello</p>
{{|/block}}
```
Block tags may also specify "else" content, separated from the main content by
the special template tag `{{|else}}`.
A block tag's content must consist of HTML with balanced tags.
Block tags can be used inside attribute values:
```
<div class="{{|#if done}}done{{|else}}notdone{{|/if}}">
...
</div>
```
### If/Unless
An `#if` template tag renders either its main content or its "else" content,
depending on the value of its data argument. Any falsy JavaScript value
(including `null`, `undefined`, `0`, `""`, and `false`) is considered false, as
well as the empty array, while any other value is considered true.
```
{{|#if something}}
<p>It's true</p>
{{|else}}
<p>It's false</p>
{{|/if}}
```
`#unless` is just `#if` with the condition inverted.
### With
A `#with` template tag establishes a new data context object for its contents.
The properties of the data context object are where Spacebars looks when
resolving template tag names.
```
{{|#with employee}}
<div>Name: {{|name}}</div>
<div>Age: {{|age}}</div>
{{|/with}}
```
We can take advantage of the object specification form of a block tag to define
an object with properties we name:
```
{{|#with x=1 y=2}}
{{|{getHTMLForPoint this}}}
{{|/with}}
```
If the argument to `#with` is falsy (by the same rules as for `#if`), the
content is not rendered. An "else" block may be provided, which will be
rendered instead.
If the argument to `#with` is a string or other non-object value, it may be
promoted to a JavaScript wrapper object (also known as a boxed value) when
passed to helpers, because JavaScript traditionally only allows an object for
`this`. Use `String(this)` to get an unboxed string value or `Number(this)` to
get an unboxed number value.
### Each
An `#each` template tag takes a sequence argument and inserts its content for
each item in the sequence, setting the data context to the value of that item:
```
<ul>
{{|#each people}}
<li>{{|name}}</li>
{{|/each}}
</ul>
```
The newer variant of `#each` doesn't change the data context but introduces a
new variable that can be used in the body to refer to the current item:
```
<ul>
{{|#each person in people}}
<li>{{|person.name}}</li>
{{|/each}}
</ul>
```
The argument is typically a Meteor cursor (the result of `collection.find()`,
for example), but it may also be a plain JavaScript array, `null`, or
`undefined`.
An "else" section may be provided, which is used (with no new data
context) if there are zero items in the sequence at any time.
You can use a special variable `@index` in the body of `#each` to get the
0-based index of the currently rendered value in the sequence.
#### Reactivity Model for Each
When the argument to `#each` changes, the DOM is always updated to reflect the
new sequence, but it's sometimes significant exactly how that is achieved. When
the argument is a Meteor live cursor, the `#each` has access to fine-grained
updates to the sequence -- add, remove, move, and change callbacks -- and the
items are all documents identified by unique ids. As long as the cursor itself
remains constant (i.e. the query doesn't change), it is very easy to reason
about how the DOM will be updated as the contents of the cursor change. The
rendered content for each document persists as long as the document is in the
cursor, and when documents are re-ordered, the DOM is re-ordered.
Things are more complicated if the argument to the `#each` reactively changes
between different cursor objects, or between arrays of plain JavaScript objects
that may not be identified clearly. The implementation of `#each` tries to be
intelligent without doing too much expensive work. Specifically, it tries to
identify items between the old and new array or cursor with the following
strategy:
1. For objects with an `_id` field, use that field as the identification key
2. For objects with no `_id` field, use the array index as the identification
key. In this case, appends are fast but prepends are slower.
3. For numbers or strings, use their value as the identification key.
In case of duplicate identification keys, all duplicates after the first are
replaced with random ones. Using objects with unique `_id` fields is the way to
get full control over the identity of rendered elements.
### Let
The `#let` tag creates a new alias variable for a given expression. While it
doesn't change the data context, it allows to refer to an expression (helper,
data context, another variable) with a short-hand within the template:
```
{{|#let name=person.bio.firstName color=generateColor}}
<div>{{|name}} gets a {{|color}} card!</div>
{{|/let}}
```
Variables introduced this way take precedence over names of templates, global
helpers, fields of the current data context and previously introduced
variables with the same name.
### Custom Block Helpers
To define your own block helper, simply declare a template, and then invoke it
using `{{|#someTemplate}}` (block) instead of `{{|> someTemplate}}` (inclusion)
syntax.
When a template is invoked as a block helper, it can use `{{|>
Template.contentBlock}}` and `{{|> Template.elseBlock}}` to include the block
content it was passed.
Here is a simple block helper that wraps its content in a div:
```
<template name="note">
<div class="note">
{{|> Template.contentBlock}}
</div>
</template>
```
You would invoke it as:
```
{{|#note}}
Any content here
{{|/note}}
```
Here is an example of implementing `#unless` in terms of `#if` (ignoring for the
moment that `unless` is a built-in directive):
```
<template name="unless">
{{|#if this}}
{{|> Template.elseBlock}}
{{|else}}
{{|> Template.contentBlock}}
{{|/if}}
</template>
```
Note that the argument to `#unless` (the condition) becomes the data context in
the `unless` template and is accessed via `this`. However, it would not work
very well if this data context was visible to `Template.contentBlock`, which is
supplied by the user of `unless`.
Therefore, when you include `{{|> Template.contentBlock}}`, Spacebars hides the
data context of the calling template, and any data contexts established in the
template by `#each` and `#with`. They are not visible to the content block,
even via `..`. Put another way, it's as if the `{{|> Template.contentBlock}}`
inclusion occurred at the location where `{{|#unless}}` was invoked, as far as
the data context stack is concerned.
You can pass an argument to `{{|> Template.contentBlock}}` or `{{|>
Template.elseBlock}}` to invoke it with a data context of your choice. You can
also use `{{|#if Template.contentBlock}}` to see if the current template was
invoked as a block helper rather than an inclusion.
### Comment Tags
Comment template tags begin with `{{|!` and can contain any characters except for
`}}`. Comments are removed upon compilation and never appear in the compiled
template code or the generated HTML.
```
{{|! Start of a section}}
<div class="section">
...
</div>
```
Comment tags also come in a "block comment" form. Block comments may contain
`{{|` and `}}`:
```
{{|!-- This is a block comment.
We can write {{|foo}} and it doesn't matter.
{{|#with x}}This code is commented out.{{|/with}}
--}}
```
Comment tags can be used wherever other template tags are allowed.
## Nested sub-expressions
Sometimes an argument to a helper call is best expressed as a return value of
some other expression. For this and other cases, one can use parentheses to
express the evaluation order of nested expressions.
```
{{|capitalize (getSummary post)}}
```
In this example, the result of the `getSummary` helper call will be passed to
the `capitalize` helper.
Sub-expressions can be used to calculate key-word arguments, too:
```
{{|> tmpl arg=(helper post)}}
```
### HTML Dialect
Spacebars templates are written in [standard
HTML](http://developers.whatwg.org/syntax.html) extended with
additional syntax (i.e. template tags).
Spacebars validates your HTML as it goes and will throw a compile-time
error if you violate basic HTML syntax in a way that prevents it from
determining the structure of your code.
Spacebars is not lenient about malformed markup the way a web browser
is. While the latest HTML spec standardizes how browsers should
recover from parse errors, these cases are still not valid HTML. For
example, a browser may recover from a bare `<` that does not begin a
well-formed HTML tag, while Spacebars will not. However, gone are the
restrictions of the XHTML days; attribute values do not have to
quoted, and tags are not case-sensitive, for example.
You must close all HTML tags except the ones specified to have no end
tag, like BR, HR, IMG and INPUT. You can write these tags as `<br>`
or equivalently `<br/>`.
The HTML spec allows omitting some additional end tags, such as P and
LI, but Spacebars doesn't currently support this.
### Top-level Elements in a `.html` file
Technically speaking, the `<{{! }}template>` element is not part of the Spacebars
language. A `foo.html` template file in Meteor consists of one or more of the
following elements:
* `<{{! }}template name="myName">` - The `<{{! }}template>` element contains a Spacebars
template (as defined in the rest of this file) which will be compiled to the
`Template.myName` component.
* `<head>` - Static HTML that will be inserted into the `<head>` element of the
default HTML boilerplate page. Cannot contain template tags. If `<head>` is
used multiple times (perhaps in different files), the contents of all of the
`<head>` elements are concatenated.
* `<body>` - A template that will be inserted into the `<body>` of the main
page. It will be compiled to the `Template.body` component. If `<body>` is
used multiple times (perhaps in different files), the contents of all of the
`<body>` elements are concatenated.
### Escaping Curly Braces
To insert a literal `{{|`, `{{|{`, or any number of curly braces, put a
vertical bar after it. So `{{||` will show up as `{{|`, `{{|{|` will
show up as `{{|{`, and so on.
{{/template}}

View File

@@ -1,32 +0,0 @@
{{#template name="pkg_underscore"}}
## `underscore`
[Underscore](http://underscorejs.org/) is a utility-belt library for
JavaScript that provides support for functional programming. It is
invaluable for writing clear, concise JavaScript in a functional style.
The `underscore` package defines the `_` namespace on both the client
and the server.
{{#warning}}
Currently, underscore is included in all projects, as the Meteor
core depends on it. _ is available in the global namespace on both the
client and the server even if you do not include this package. However
if you do use underscore in your application, you should still add the
package as we will remove the default underscore in the future.
{{/warning}}
{{#warning}}
We have slightly modified the way Underscore differentiates between
objects and arrays in [collection functions](http://underscorejs.org/#each).
The original Underscore logic is to treat any object with a numeric `length`
property as an array (which helps it work properly on
[`NodeList`s](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)).
In Meteor's version of Underscore, objects with a numeric `length` property
are treated as objects if they have no prototype (specifically, if
`x.constructor === Object`.
{{/warning}}
{{/template}}

View File

@@ -1,45 +0,0 @@
{{#template name="pkg_webapp"}}
## `webapp`
The `webapp` package is what lets your Meteor app serve content to a web
browser. It is included in the `meteor-base` set of packages that is
automatically added when you run `meteor create`. You can easily build a
Meteor app without it - for example if you wanted to make a command-line
tool that still used the Meteor package system and DDP.
This package also allows you to add handlers for HTTP requests.
This lets other services access your app's data through an HTTP API, allowing
it to easily interoperate with tools and frameworks that don't yet support DDP.
`webapp` exposes the [connect](https://github.com/senchalabs/connect) API for
handling requests through `WebApp.connectHandlers`.
Here's an example that will let you handle a specific URL:
```js
// Listen to incoming HTTP requests, can only be used on the server
WebApp.connectHandlers.use("/hello", function(req, res, next) {
res.writeHead(200);
res.end("Hello world from: " + Meteor.release);
});
```
`WebApp.connectHandlers.use([path], handler)` has two arguments:
**path** - an optional path field.
This handler will only be called on paths that match
this string. The match has to border on a `/` or a `.`. For example, `/hello`
will match `/hello/world` and `/hello.world`, but not `/hello_world`.
**handler** - this is a function that takes three arguments:
- **req** - a Node.js
[IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage)
object with some extra properties. This argument can be used to get information
about the incoming request.
- **res** - a Node.js
[ServerResponse](http://nodejs.org/api/http.html#http_class_http_serverresponse)
object. Use this to write data that should be sent in response to the
request, and call `res.end()` when you are done.
- **next** - a function. Calling this function will pass on the handling of
this request to the next relevant handler.
{{/template}}

View File

@@ -1,42 +0,0 @@
<template name="tableOfContents">
<div class="full-api-toc">
{{> nav}}
</div>
</template>
<template name="nav">
{{#each sections}}
{{#if type "spacer"}}
<div class="spacer"> </div>
{{/if}}
{{#if type "section"}}
{{#nav_section}}
<a href="{{link}}" class="{{maybe_current}} {{style}}">
{{#if prefix}}{{prefix}}.{{/if}}{{#if instance}}<i>{{instance}}</i>.{{/if}}{{name}}
</a>
{{/nav_section}}
{{/if}}
{{/each}}
</template>
<template name="nav_section">
{{#if depthIs 1}}
<h1>{{> UI.contentBlock}}</h1>
{{/if}}
{{#if depthIs 2}}
<h2>{{> UI.contentBlock}}</h2>
{{/if}}
{{#if depthIs 3}}
<h3>{{> UI.contentBlock}}</h3>
{{/if}}
{{#if depthIs 4}}
<h4>{{> UI.contentBlock}}</h4>
{{/if}}
{{#if depthIs 5}}
<h5>{{> UI.contentBlock}}</h5>
{{/if}}
{{#if depthIs 6}}
<h6>{{> UI.contentBlock}}</h6>
{{/if}}
</template>

View File

@@ -1,430 +0,0 @@
var toc = [
[
"Meteor Guide",
],
"API", [
"Core", [
"Meteor.isClient",
"Meteor.isServer",
"Meteor.isCordova",
{ name: "Meteor.isDevelopment", id: "Meteor-isDevelopment" },
{ name: "Meteor.isProduction", id: "Meteor-isProduction" },
"Meteor.startup",
"Meteor.wrapAsync",
"Meteor.defer",
"Meteor.absoluteUrl",
"Meteor.settings",
"Meteor.release"
],
"Publish and subscribe", [
"Meteor.publish", [
{instance: "this", name: "userId", id: "publish_userId"},
{instance: "this", name: "added", id: "publish_added"},
{instance: "this", name: "changed", id: "publish_changed"},
{instance: "this", name: "removed", id: "publish_removed"},
{instance: "this", name: "ready", id: "publish_ready"},
{instance: "this", name: "onStop", id: "publish_onstop"},
{instance: "this", name: "error", id: "publish_error"},
{instance: "this", name: "stop", id: "publish_stop"},
{instance: "this", name: "connection", id: "publish_connection"}
],
"Meteor.subscribe",
{name: "DDPRateLimiter", id: "ddpratelimiter"}
],
{name: "Methods", id: "methods_header"}, [
"Meteor.methods", [
{instance: "this", name: "userId", id: "method_userId"},
{instance: "this", name: "setUserId", id: "method_setUserId"},
{instance: "this", name: "isSimulation", id: "method_issimulation"},
{instance: "this", name: "unblock", id: "method_unblock"},
{instance: "this", name: "connection", id: "method_connection"}
],
"Meteor.Error",
"Meteor.call",
"Meteor.apply",
{name: "DDPRateLimiter", id: "ddpratelimiter"}
],
{name: "Check", id: "check_package"}, [
"check",
"Match.test",
{name: "Match patterns", style: "noncode"}
],
{name: "Server connections", id: "connections"}, [
"Meteor.status",
"Meteor.reconnect",
"Meteor.disconnect",
"Meteor.onConnection",
"DDP.connect"
],
{name: "Collections", id: "collections"}, [
"Mongo.Collection", [
{instance: "collection", name: "find"},
{instance: "collection", name: "findOne"},
{instance: "collection", name: "insert"},
{instance: "collection", name: "update"},
{instance: "collection", name: "upsert"},
{instance: "collection", name: "remove"},
{instance: "collection", name: "allow"},
{instance: "collection", name: "deny"},
{instance: "collection", name: "rawCollection",
id: "Mongo-Collection-rawCollection"},
{instance: "collection", name: "rawDatabase",
id: "Mongo-Collection-rawDatabase"}
],
"Mongo.Cursor", [
{instance: "cursor", name: "forEach"},
{instance: "cursor", name: "map"},
{instance: "cursor", name: "fetch"},
{instance: "cursor", name: "count"},
{instance: "cursor", name: "observe"},
{instance: "cursor", name: "observeChanges", id: "observe_changes"}
],
{type: "spacer"},
{name: "Mongo.ObjectID", id: "mongo_object_id"},
{type: "spacer"},
{name: "Selectors", style: "noncode"},
{name: "Modifiers", style: "noncode"},
{name: "Sort specifiers", style: "noncode"},
{name: "Field specifiers", style: "noncode"}
],
"Session", [
"Session.set",
{name: "Session.setDefault", id: "session_set_default"},
"Session.get",
"Session.equals"
],
{name: "Accounts", id: "accounts_api"}, [
"Meteor.user",
"Meteor.userId",
"Meteor.users",
"Meteor.loggingIn",
"Meteor.logout",
"Meteor.logoutOtherClients",
"Meteor.loginWithPassword",
{name: "Meteor.loginWith<Service>", id: "meteor_loginwithexternalservice"},
{type: "spacer"},
{name: "{{currentUser}}", id: "template_currentuser"},
{name: "{{loggingIn}}", id: "template_loggingin"},
{type: "spacer"},
"Accounts.ui.config"
],
{name: "Accounts (multi-server)", id: "advanced_accounts_api"}, [
"AccountsClient",
"AccountsServer",
{type: "spacer"},
{ name: "AccountsCommon#userId", id: "accounts_userid" },
{ name: "AccountsCommon#user", id: "accounts_user" },
{ name: "AccountsCommon#config", id: "accounts_config" },
{ name: "AccountsCommon#onLogin", id: "accounts_onlogin" },
{ name: "AccountsCommon#onLoginFailure", id: "accounts_onloginfailure" },
{type: "spacer"},
{ name: "AccountsClient#loggingIn", id: "accounts_loggingin" },
{ name: "AccountsClient#logout", id: "accounts_logout" },
{ name: "AccountsClient#logoutOtherClients", id: "accounts_logoutotherclients" },
{type: "spacer"},
{ name: "AccountsServer#onCreateUser",
id: "accounts_oncreateuser" },
{ name: "AccountsServer#validateLoginAttempt",
id: "accounts_validateloginattempt" },
{ name: "AccountsServer#validateNewUser",
id: "accounts_validatenewuser" },
],
{name: "Passwords", id: "accounts_passwords"}, [
"Accounts.createUser",
{type: "spacer"},
{name: "Accounts.setUsername", id: "Accounts-setUsername"},
{name: "Accounts.addEmail", id: "Accounts-addEmail"},
{name: "Accounts.removeEmail", id: "Accounts-removeEmail"},
{name: "Accounts.verifyEmail", id: "accounts_verifyemail"},
{name: "Accounts.findUserByUsername", id: "Accounts-findUserByUsername"},
{name: "Accounts.findUserByEmail", id: "Accounts-findUserByEmail"},
{type: "spacer"},
"Accounts.changePassword",
"Accounts.forgotPassword",
"Accounts.resetPassword",
"Accounts.setPassword",
{type: "spacer"},
"Accounts.sendResetPasswordEmail",
"Accounts.sendEnrollmentEmail",
"Accounts.sendVerificationEmail",
{type: "spacer"},
{name: "Accounts.onResetPasswordLink", id: "Accounts-onResetPasswordLink"},
{name: "Accounts.onEnrollmentLink", id: "Accounts-onEnrollmentLink"},
{name: "Accounts.onEmailVerificationLink", id: "Accounts-onEmailVerificationLink"},
{type: "spacer"},
"Accounts.emailTemplates"
],
{name: "Templates", id: "templates_api"}, [
{prefix: "Template", instance: "myTemplate", id: "templates_api"}, [
{name: "events", id: "template_events"},
{name: "helpers", id: "template_helpers"},
{name: "onRendered", id: "template_onRendered"},
{name: "onCreated", id: "template_onCreated"},
{name: "onDestroyed", id: "template_onDestroyed"}
],
{name: "Template instances", id: "template_inst"}, [
{instance: "template", name: "findAll", id: "template_findAll"},
{instance: "template", name: "$", id: "template_$"},
{instance: "template", name: "find", id: "template_find"},
{instance: "template", name: "firstNode", id: "template_firstNode"},
{instance: "template", name: "lastNode", id: "template_lastNode"},
{instance: "template", name: "data", id: "template_data"},
{instance: "template", name: "autorun", id: "template_autorun"},
{instance: "template", name: "subscribe", id: "Blaze-TemplateInstance-subscribe"},
{instance: "template", name: "view", id: "template_view"}
],
"Template.registerHelper",
"Template.instance",
"Template.currentData",
"Template.parentData",
"Template.body",
{name: "{{> Template.dynamic}}", id: "template_dynamic"},
{type: "spacer"},
{name: "Event maps", style: "noncode"},
{name: "Spacebars", style: "noncode"}
],
"Blaze", [
"Blaze.render",
"Blaze.renderWithData",
"Blaze.remove",
"Blaze.getData",
"Blaze.toHTML",
"Blaze.toHTMLWithData",
"Blaze.View", [
"Blaze.currentView",
"Blaze.getView",
"Blaze.With",
"Blaze.If",
"Blaze.Unless",
"Blaze.Each"
],
"Blaze.Template",
"Blaze.isTemplate",
{type: "spacer"},
{name: "Renderable content", id: "renderable_content", style: "noncode"}
],
"Timers", [
"Meteor.setTimeout",
"Meteor.setInterval",
"Meteor.clearTimeout",
"Meteor.clearInterval"
],
"Tracker", [
"Tracker.autorun",
"Tracker.flush",
"Tracker.nonreactive",
"Tracker.active",
"Tracker.currentComputation",
"Tracker.onInvalidate",
"Tracker.afterFlush",
"Tracker.Computation", [
{instance: "computation", name: "stop", id: "computation_stop"},
{instance: "computation", name: "invalidate", id: "computation_invalidate"},
{instance: "computation", name: "onInvalidate", id: "computation_oninvalidate"},
{instance: "computation", name: "onStop", id: "computation_onstop"},
{instance: "computation", name: "stopped", id: "computation_stopped"},
{instance: "computation", name: "invalidated", id: "computation_invalidated"},
{instance: "computation", name: "firstRun", id: "computation_firstrun"}
],
"Tracker.Dependency", [
{instance: "dependency", name: "changed", id: "dependency_changed"},
{instance: "dependency", name: "depend", id: "dependency_depend"},
{instance: "dependency", name: "hasDependents", id: "dependency_hasdependents"}
]
],
{name: "ReactiveVar", id: "reactivevar_pkg"}, [
"ReactiveVar",
{instance: "reactiveVar", name: "get", id: "reactivevar_get"},
{instance: "reactiveVar", name: "set", id: "reactivevar_set"}
],
// "Environment Variables", [
// "Meteor.EnvironmentVariable", [
// {instance: "env_var", name: "get", id: "env_var_get"},
// {instance: "env_var", name: "withValue", id: "env_var_withvalue"},
// {instance: "env_var", name: "bindEnvironment", id: "env_var_bindenvironment"}
// ]
//],
{name: "EJSON", id: "ejson"}, [
{name: "EJSON.parse", id: "ejson_parse"},
{name: "EJSON.stringify", id: "ejson_stringify"},
{name: "EJSON.fromJSONValue", id: "ejson_from_json_value"},
{name: "EJSON.toJSONValue", id: "ejson_to_json_value"},
{name: "EJSON.equals", id: "ejson_equals"},
{name: "EJSON.clone", id: "ejson_clone"},
{name: "EJSON.newBinary", id: "ejson_new_binary"},
{name: "EJSON.isBinary", id: "ejson_is_binary"},
{name: "EJSON.addType", id: "ejson_add_type"},
[
{instance: "customType", id: "ejson_type_typeName", name: "typeName"},
{instance: "customType", id: "ejson_type_toJSONValue", name: "toJSONValue"},
{instance: "customType", id: "ejson_type_clone", name: "clone"},
{instance: "customType", id: "ejson_type_equals", name: "equals"}
]
],
"HTTP", [
"HTTP.call",
{name: "HTTP.get"},
{name: "HTTP.post"},
{name: "HTTP.put"},
{name: "HTTP.del"}
],
"Email", [
"Email.send"
],
{name: "Assets", id: "assets"}, [
{name: "Assets.getText", id: "assets_getText"},
{name: "Assets.getBinary", id: "assets_getBinary"}
],
{name: "package.js", id: "packagejs"}, [
{name: "Package.describe", id: "packagedescription"},
{name: "Package.onUse", id: "packagedefinition"}, [
{name: "api.versionsFrom", id: "pack_versions"},
{name: "api.use", id: "pack_use"},
{name: "api.imply", id: "pack_api_imply"},
{name: "api.export", id: "pack_export"},
{name: "api.addFiles", id: "pack_addFiles"},
{name: "api.addAssets", id: "PackageAPI-addAssets"}
],
{name: "Package.onTest", id: "packagetests"},
{name: "Npm.depends", id: "Npm-depends"},
{name: "Npm.require", id: "Npm-require"},
{name: "Cordova.depends", id: "Cordova-depends"},
{name: "Package.registerBuildPlugin", id: "Package-registerBuildPlugin"}, [
{name: "Plugin.registerSourceHandler", id: "Plugin-registerSourceHandler"}
]
],
{name: "mobile-config.js", id: "mobileconfigjs"}, [
{name: "App.info", id: "App-info"},
{name: "App.setPreference", id: "App-setPreference"},
{name: "App.accessRule", id: "App-accessRule"},
{name: "App.configurePlugin", id: "App-configurePlugin"},
{name: "App.icons", id: "App-icons"},
{name: "App.launchScreens", id: "App-launchScreens"}
]
],
"Packages", [ [
"appcache",
"accounts-ui",
"audit-argument-checks",
"coffeescript",
"ecmascript",
"jquery",
"less",
"markdown",
"modules",
"oauth-encryption",
"random",
{name: "spacebars", id: "pkg_spacebars"},
{name: "spiderable", link: "https://atmospherejs.com/meteor/spiderable"},
"underscore",
"webapp"
] ],
"Command line", [ [
"meteor help",
"meteor run",
"meteor debug",
"meteor create",
"meteor login / logout",
"meteor deploy",
"meteor update",
"meteor add",
"meteor remove",
"meteor list",
"meteor mongo",
"meteor reset",
"meteor build",
"meteor lint",
"meteor search",
"meteor show",
"meteor publish",
"meteor publish-for-arch",
"meteor publish-release",
"meteor test-packages",
"meteor admin",
"meteor shell"
] ]
];
var name_to_id = function (name) {
var x = name.toLowerCase().replace(/[^a-z0-9_,.]/g, '').replace(/[,.]/g, '_');
return x;
};
Template.nav.helpers({
sections: function () {
var ret = [];
var walk = function (items, depth) {
_.each(items, function (item) {
// Work around (eg) accidental trailing commas leading to spurious holes
// in IE8.
if (!item)
return;
if (item instanceof Array)
walk(item, depth + 1);
else {
if (typeof(item) === "string")
item = {name: item};
var id = item.id || (item.name && name_to_id(item.name)) || "";
ret.push(_.extend({
type: "section",
link: "#/full/" + id,
depth: depth,
style: ''
}, item));
}
});
};
walk(toc, 1);
return ret;
},
type: function (what) {
return this.type === what;
},
maybe_current: function () {
return Session.get('urlHash').split('/')[2] === this.id ? 'current' : '';
}
});
Template.nav_section.helpers({
depthIs: function (n) {
return this.depth === n;
}
});

View File

@@ -1,64 +0,0 @@
/** Section nav **/
#nav-inner {
padding-left: 30px;
padding-right: 30px;
padding-top: -10px;
padding-bottom: 30px;
}
.full-api-toc {
line-height: 1.2;
a {
text-decoration: none;
color: black;
}
a:hover {
margin: 0px -5px 0px -5px;
padding: 2px 5px 2px 5px;
}
h1 {
font-size: 1.7em;
margin: 1.2em 0 .2em 0;
}
h2 {
font-size: 1.2em;
font-weight: normal;
margin: .3em 0 0 0;
}
h3 {
font-size: .8em;
font-weight: normal;
margin: 4px 0px 2px 0px;
padding-left: 10px;
color: #333333;
}
h4 {
font-size: .8em;
font-weight: normal;
margin: 4px 0px 4px 0px;
padding-left: 20px;
color: #333333;
}
.spacer {
height: .33em;
}
.noncode {
font-style: italic;
}
.current {
color: red;
}
}

View File

@@ -1,19 +0,0 @@
release = Meteor.release ? "1.3" : "(checkout)";
Template.registerHelper("release", release);
Template.registerHelper("fullApi", function () {
return Session.get("fullApi");
});
Template.registerHelper('dstache', function() {
return '{{';
});
Template.registerHelper('tstache', function() {
return '{{{';
});
Template.registerHelper('lt', function () {
return '<';
});

View File

@@ -1,72 +0,0 @@
<head>
<title>Documentation - Meteor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="Description"
content="Meteor is an open-source JavaScript platform for building top-quality web apps in a fraction of the time, whether you're an expert developer or just getting started."/>
<link rel="icon" href="/favicon.png" type="image/png" />
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-M2CMWR"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-M2CMWR');</script>
<!-- End Google Tag Manager -->
<!-- Start of Async HubSpot Analytics Code -->
<script type="text/javascript">
(function(d,s,i,r) {
if (d.getElementById(i)){return;}
var n=d.createElement(s),e=d.getElementsByTagName(s)[0];
n.id=i;n.src='//js.hs-analytics.net/analytics/'+(Math.ceil(new Date()/r)*r)+'/520701.js';
e.parentNode.insertBefore(n, e);
})(document,"script","hs-analytics",300000);
</script>
<!-- End of Async HubSpot Analytics Code -->
</head>
<body>
<div class="body {{openSidebar}}">
{{> search}}
<div id="nav">
{{> sidebar}}
</div>
<div class="overlay close-sidebar"></div>
{{> topBar}}
<div class="main-content">
<div id="main">
<div><div id="top"></div></div>
<div>
{{> fullApiContent}}
</div>
</div>
</div>
</div>
</body>
<template name="sidebar">
<div id="nav-inner">
<h1>
<a href="#/full">
<img src="/logo.png" class="logo" alt="Meteor" />
<div>{{release}} Docs</div>
</a>
</h1>
{{> tableOfContents}}
</div>
</template>
<template name="topBar">
<div class="top-bar">
<div class="hamburger-menu-target open-sidebar">
<div class="hamburger-menu"></div>
</div>
<h1>
<img src="/logo.png" class="logo" alt="Meteor" /> {{release}} Docs
</h1>
</div>
</template>

View File

@@ -1,3 +0,0 @@
navigate = function (hash) {
window.location.replace(Meteor.absoluteUrl() + hash);
};

View File

@@ -1,145 +0,0 @@
// make links backwards compatible - for example, #deps -> #tracker
// Links from the old basic API into the closest full-api section
var BASIC_TO_FULL_LINKS = {
'learning-resources': 'guide',
'command-line': 'commandline',
'templates': 'templates_api',
'defining-templates': 'templates_api',
'Template-helpers': 'template_helpers',
'Template-events': 'template_events',
'Template-onRendered': 'template_onRendered',
'Blaze-TemplateInstance-findAll': 'template_findAll',
'Blaze-TemplateInstance-find': 'template_find',
'session': 'session',
'Session-set': 'session_set',
'Session-get': 'session_get',
'tracker': 'tracker',
'Tracker-autorun': 'tracker_autorun',
'collections': 'collections',
'Mongo-Collection': 'mongo_collection',
'Mongo-Collection-findOne': 'findone',
'Mongo-Collection-find': 'find',
'Mongo-Collection-insert': 'insert',
'Mongo-Collection-update': 'update',
'Mongo-Collection-remove': 'remove',
'Mongo-Collection-allow': 'allow',
'Mongo-Collection-deny': 'deny',
'accounts': 'accounts_api',
'loginButtons': 'accountsui',
'Meteor-user': 'meteor_user',
'Meteor-userId': 'meteor_userid',
'Meteor-users': 'meteor_users',
'currentUser': 'template_currentuser',
'methods': 'methods_header',
'Meteor-methods': 'meteor_methods',
'Meteor-call': 'meteor_call',
'Meteor-Error': 'meteor_error',
'pubsub': 'publishandsubscribe',
'Meteor-publish': 'meteor_publish',
'Meteor-subscribe': 'meteor_subscribe',
'environment': 'core',
'Meteor-isClient': 'meteor_isclient',
'Meteor-isServer': 'meteor_isserver',
'Meteor-startup': 'meteor_startup',
'packages': 'packages',
'searchingforpackages': 'packages',
'accountsui': 'accountsui',
'coffeescript': 'coffeescript',
'email': 'email',
'jquery': 'jquery',
'http': 'http',
'less': 'less',
'markdown': 'markdown',
'underscore': 'underscore',
'spiderable': 'spiderable',
};
var BASIC_TO_GUIDE_LINKS = {
filestructure: 'structure.html',
buildingmobileapps: 'mobile.html',
quickstart: '#quickstart',
};
var FULL_TO_GUIDE_LINKS = {
whatismeteor: '#what-is-meteor',
sevenprinciples: '#what-is-meteor',
quickstart: '#quickstart',
structuringyourapp: 'structure.html',
dataandsecurity: 'security.html',
livehtmltemplates: '#what-is-meteor',
usingpackages: 'user-packages.html',
namespacing: 'structure.html',
deploying: 'deployment.html',
writingpackages: 'writing-packages.html',
};
Meteor.startup(function () {
var getRedirect = function (hash) {
if (hash.indexOf("deps") !== -1) {
return hash.replace("deps", "tracker");
}
if (hash.indexOf("_created") !== -1) {
return hash.replace("_created", "_onCreated");
}
if (hash.indexOf("_rendered") !== -1) {
return hash.replace("_rendered", "_onRendered");
}
if (hash.indexOf("_destroyed") !== -1) {
return hash.replace("_destroyed", "_onDestroyed");
}
if (hash === "meteor_collection") {
return "mongo_collection";
}
if (hash === "collection_object_id") {
return "mongo_object_id";
}
if (hash === "match") {
return "check_package";
}
if (hash === "meteorbundle") {
return "meteorbuild";
}
if (hash.indexOf("reactivity") !== -1) {
return "/full/tracker";
}
var parts = hash.split('/');
if (parts[1] === 'basic') {
var fullLink = BASIC_TO_FULL_LINKS[parts[2]];
if (fullLink) {
return 'full/' + fullLink;
}
var guideLink = BASIC_TO_GUIDE_LINKS[parts[2]];
if (guideLink) {
window.location.replace('http://guide.meteor.com/' + guideLink);
}
}
if (parts[1] === 'full') {
var guideLink = FULL_TO_GUIDE_LINKS[parts[2]];
if (guideLink) {
window.location.replace('http://guide.meteor.com/' + guideLink);
}
}
// don't redirect
return false;
};
var curLink = window.location.hash.slice(1);
var redirect = getRedirect(curLink);
if (redirect) {
window.location = "#" + redirect;
}
});

View File

@@ -1,155 +0,0 @@
var ignoreUrlChange = false;
var ignoreWaypoints = true;
var deHash = function (hashString) {
return hashString.slice(1);
};
Session.setDefault('urlHash', location.hash);
$(window).on('hashchange', function () {
Session.set('urlHash', location.hash);
});
// need an actual function to only debounce inside the if statement
var actuallyUpdateUrl = _.debounce(function (el) {
var docsType = Session.get("fullApi") ? "full" : "basic";
var newHash = "#/" + docsType + "/" + el.id;
if (window.location.hash !== newHash) {
ignoreUrlChange = true;
window.location.replace(newHash);
}
}, 100);
var updateUrlFromWaypoint = function (el) {
if (! ignoreWaypoints) {
actuallyUpdateUrl(el);
}
};
Tracker.autorun(function () {
// returns a "location" like object with all of the url parts
var current = Session.get('urlHash');
// If the URL changes from a waypoint, do nothing
if (ignoreUrlChange) {
ignoreUrlChange = false;
return;
}
// If the URL changes, close the sidebar
Session.set("sidebarOpen", false);
// redirect routes with no trailing slash
if (current === "#/basic") {
navigate("#/basic/");
return;
} else if (current === "#/full") {
navigate("#/full/");
return;
}
if (current.match(/^#\/basic\//)) {
Session.set("fullApi", false);
} else if (current.match(/^#\/full\//)) {
Session.set("fullApi", true);
} else {
if (current) {
// XXX COMPAT WITH old docs
navigate("#/full/" + deHash(current));
} else {
if (localStorage.getItem("fullApi") === "true") {
navigate("#/full/");
} else {
navigate("#/basic/");
}
}
return;
}
Tracker.afterFlush(function () {
setTimeout(function () {
var id = current.split('/')[2];
var targetLocation = 0;
if (id) {
// XXX this selector is tied to the structure of the document so tightly
// because sometimes we have two elements with the same id.
// For example: "Quick start" section appears in both basic docs and full
// docs. Since we hide parts of DOM with CSS the user doesn't see both at
// the same time but they are still both in the DOM. New browsers allow us
// to query by id even if ids repeat themselves. We cannot change it
// easily because the markdown parser always produces an id for headings.
var cssEscape = function (selector) {
// XXX maybe use https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js?
return selector.replace(/\$/g, "\\$");
};
var selector = "#main>:not(.hidden) #" + cssEscape(id);
var foundElement = $(selector);
if (foundElement.get(0)) {
targetLocation = $(".main-content").scrollTop() + foundElement.offset().top - $(".main-content").offset().top;
}
}
ignoreWaypoints = true;
$(".main-content").animate({
scrollTop: targetLocation
}, 500, function () {
ignoreWaypoints = false;
});
}, 0);
});
});
// Remember which docs page (full or basic) we were on last, and use it as
// the default next time when we visit docs.meteor.com
//
// Make sure that this block is below the initial URL logic
Tracker.autorun(function () {
localStorage.setItem("fullApi", !! Session.get("fullApi"));
});
var setHashFromCurrentPosition = _.debounce(function () {
var tocClass = Session.get("fullApi") ? ".full-api-toc" : ".basic-toc";
// get all IDs that are linked to from sidebar
var ids = {};
$("#nav " + tocClass + " a").each(function (i, el) {
ids[_.last(el.href.split("/"))] = true;
});
var pageEls = $('.main-content :not(.hidden) [id]');
var correctIndex = -1;
var lastIndex = -1;
// how far from the top of the page is the waypoint triggered?
var distanceFromTop = 150;
pageEls.each(function (i, el) {
if (! ids[el.id]) {
// only add waypoints to things that have sidebar links
return;
}
if ($(el).offset().top > distanceFromTop) {
if (correctIndex === -1) { // don't do this twice
// If this element is below the cutoff, we want to set the URL to
// link to the previous element
correctIndex = lastIndex;
}
}
lastIndex = i;
});
if (correctIndex !== -1) {
updateUrlFromWaypoint(pageEls[correctIndex]);
}
}, 200);
Template.body.events({
"scroll .main-content": function () {
setHashFromCurrentPosition();
}
});

View File

@@ -1,294 +0,0 @@
[
"Accounts",
"Accounts",
"Accounts.addEmail",
"Accounts.changePassword",
"Accounts.createUser",
"Accounts.emailTemplates",
"Accounts.findUserByEmail",
"Accounts.findUserByUsername",
"Accounts.forgotPassword",
"Accounts.onEmailVerificationLink",
"Accounts.onEnrollmentLink",
"Accounts.onResetPasswordLink",
"Accounts.removeEmail",
"Accounts.resetPassword",
"Accounts.sendEnrollmentEmail",
"Accounts.sendResetPasswordEmail",
"Accounts.sendVerificationEmail",
"Accounts.setPassword",
"Accounts.setUsername",
"Accounts.ui",
"Accounts.ui.config",
"Accounts.verifyEmail",
"AccountsClient",
"AccountsClient#config",
"AccountsClient#loggingIn",
"AccountsClient#logout",
"AccountsClient#logoutOtherClients",
"AccountsClient#onLogin",
"AccountsClient#onLoginFailure",
"AccountsClient#user",
"AccountsClient#userId",
"AccountsCommon",
"AccountsCommon#config",
"AccountsCommon#onLogin",
"AccountsCommon#onLoginFailure",
"AccountsCommon#user",
"AccountsCommon#userId",
"AccountsServer",
"AccountsServer#config",
"AccountsServer#onCreateUser",
"AccountsServer#onLogin",
"AccountsServer#onLoginFailure",
"AccountsServer#user",
"AccountsServer#userId",
"AccountsServer#validateLoginAttempt",
"AccountsServer#validateNewUser",
"App",
"App.accessRule",
"App.configurePlugin",
"App.icons",
"App.info",
"App.launchScreens",
"App.setPreference",
"Assets",
"Assets.getBinary",
"Assets.getText",
"Blaze",
"Blaze.Each",
"Blaze.If",
"Blaze.Let",
"Blaze.Template",
"Blaze.TemplateInstance",
"Blaze.TemplateInstance#$",
"Blaze.TemplateInstance#autorun",
"Blaze.TemplateInstance#data",
"Blaze.TemplateInstance#find",
"Blaze.TemplateInstance#findAll",
"Blaze.TemplateInstance#firstNode",
"Blaze.TemplateInstance#lastNode",
"Blaze.TemplateInstance#subscribe",
"Blaze.TemplateInstance#subscriptionsReady",
"Blaze.TemplateInstance#view",
"Blaze.Unless",
"Blaze.View",
"Blaze.With",
"Blaze.currentView",
"Blaze.getData",
"Blaze.getView",
"Blaze.isTemplate",
"Blaze.remove",
"Blaze.render",
"Blaze.renderWithData",
"Blaze.toHTML",
"Blaze.toHTMLWithData",
"CompileStep",
"CompileStep#addAsset",
"CompileStep#addHtml",
"CompileStep#addJavaScript",
"CompileStep#addStylesheet",
"CompileStep#arch",
"CompileStep#declaredExports",
"CompileStep#error",
"CompileStep#fileOptions",
"CompileStep#fullInputPath",
"CompileStep#inputPath",
"CompileStep#inputSize",
"CompileStep#packageName",
"CompileStep#pathForSourceMap",
"CompileStep#read",
"CompileStep#rootOutputPath",
"Cordova",
"Cordova.depends",
"DDP",
"DDP.connect",
"DDPCommon",
"DDPCommon.MethodInvocation",
"DDPCommon.MethodInvocation#connection",
"DDPCommon.MethodInvocation#isSimulation",
"DDPCommon.MethodInvocation#setUserId",
"DDPCommon.MethodInvocation#unblock",
"DDPCommon.MethodInvocation#userId",
"DDPRateLimiter.addRule",
"DDPRateLimiter.removeRule",
"DDPRateLimiter.setErrorMessage",
"EJSON",
"EJSON.CustomType",
"EJSON.CustomType#clone",
"EJSON.CustomType#equals",
"EJSON.CustomType#toJSONValue",
"EJSON.CustomType#typeName",
"EJSON.addType",
"EJSON.clone",
"EJSON.equals",
"EJSON.fromJSONValue",
"EJSON.isBinary",
"EJSON.newBinary",
"EJSON.parse",
"EJSON.stringify",
"EJSON.toJSONValue",
"Email.send",
"HTTP.call",
"HTTP.del",
"HTTP.get",
"HTTP.patch",
"HTTP.post",
"HTTP.put",
"InputFile#addAsset",
"InputFile#addHtml",
"InputFile#addJavaScript",
"InputFile#addStylesheet",
"InputFile#error",
"InputFile#getArch",
"InputFile#getBasename",
"InputFile#getContentsAsBuffer",
"InputFile#getContentsAsString",
"InputFile#getDeclaredExports",
"InputFile#getDirname",
"InputFile#getDisplayPath",
"InputFile#getExtension",
"InputFile#getFileOptions",
"InputFile#getPackageName",
"InputFile#getPathInBundle",
"InputFile#getPathInPackage",
"InputFile#getSourceHash",
"InputFile#getSourceMap",
"IterationCallback",
"Match",
"Match.test",
"Meteor",
"Meteor.Error",
"Meteor.absoluteUrl",
"Meteor.apply",
"Meteor.call",
"Meteor.clearInterval",
"Meteor.clearTimeout",
"Meteor.defer",
"Meteor.disconnect",
"Meteor.isClient",
"Meteor.isCordova",
"Meteor.isDevelopment",
"Meteor.isProduction",
"Meteor.isServer",
"Meteor.loggingIn",
"Meteor.loginWith<ExternalService>",
"Meteor.loginWithPassword",
"Meteor.logout",
"Meteor.logoutOtherClients",
"Meteor.methods",
"Meteor.onConnection",
"Meteor.publish",
"Meteor.reconnect",
"Meteor.release",
"Meteor.setInterval",
"Meteor.setTimeout",
"Meteor.settings",
"Meteor.startup",
"Meteor.status",
"Meteor.subscribe",
"Meteor.user",
"Meteor.userId",
"Meteor.users",
"Meteor.users",
"Meteor.wrapAsync",
"Mongo",
"Mongo.Collection",
"Mongo.Collection#allow",
"Mongo.Collection#deny",
"Mongo.Collection#find",
"Mongo.Collection#findOne",
"Mongo.Collection#insert",
"Mongo.Collection#rawCollection",
"Mongo.Collection#rawDatabase",
"Mongo.Collection#remove",
"Mongo.Collection#update",
"Mongo.Collection#upsert",
"Mongo.Cursor",
"Mongo.Cursor#count",
"Mongo.Cursor#fetch",
"Mongo.Cursor#forEach",
"Mongo.Cursor#map",
"Mongo.Cursor#observe",
"Mongo.Cursor#observeChanges",
"Mongo.ObjectID",
"Npm",
"Npm.depends",
"Npm.require",
"Package",
"Package.describe",
"Package.onTest",
"Package.onUse",
"Package.registerBuildPlugin",
"PackageAPI",
"PackageAPI#addAssets",
"PackageAPI#addFiles",
"PackageAPI#export",
"PackageAPI#imply",
"PackageAPI#use",
"PackageAPI#versionsFrom",
"Plugin",
"Plugin.registerCompiler",
"Plugin.registerLinter",
"Plugin.registerMinifier",
"Plugin.registerSourceHandler",
"ReactiveVar",
"ReactiveVar#get",
"ReactiveVar#set",
"Session.equals",
"Session.get",
"Session.set",
"Session.setDefault",
"Subscription",
"Subscription#added",
"Subscription#changed",
"Subscription#connection",
"Subscription#error",
"Subscription#onStop",
"Subscription#ready",
"Subscription#removed",
"Subscription#stop",
"Subscription#userId",
"Template",
"Template#created",
"Template#destroyed",
"Template#events",
"Template#helpers",
"Template#onCreated",
"Template#onDestroyed",
"Template#onRendered",
"Template#rendered",
"Template.body",
"Template.currentData",
"Template.deregisterHelper",
"Template.dynamic",
"Template.instance",
"Template.parentData",
"Template.registerHelper",
"Tracker",
"Tracker.Computation",
"Tracker.Computation#firstRun",
"Tracker.Computation#invalidate",
"Tracker.Computation#invalidated",
"Tracker.Computation#onInvalidate",
"Tracker.Computation#onStop",
"Tracker.Computation#stop",
"Tracker.Computation#stopped",
"Tracker.ComputationFunction",
"Tracker.Dependency",
"Tracker.Dependency#changed",
"Tracker.Dependency#depend",
"Tracker.Dependency#hasDependents",
"Tracker.active",
"Tracker.afterFlush",
"Tracker.autorun",
"Tracker.currentComputation",
"Tracker.flush",
"Tracker.nonreactive",
"Tracker.onInvalidate",
"check",
"currentUser",
"execFileAsync",
"execFileSync",
"loggingIn"
]

View File

@@ -1,14 +0,0 @@
Template.body.events({
"click .open-sidebar": function () {
Session.set("sidebarOpen", true);
},
"click .close-sidebar": function () {
Session.set("sidebarOpen", false);
}
});
Template.body.helpers({
openSidebar: function () {
return Session.get("sidebarOpen") ? "sidebar-open" : "sidebar-closed";
}
});

View File

@@ -1,20 +0,0 @@
<template name="search">
{{#if searchOpen}}
<div class="search-overlay">
<div class="search-box">
<a href="#" class="close-search"><span class="hotkey">[esc]</span> &times;</a>
<h3>Search Documentation</h3>
<input type="text" class="search-query" />
</div>
<ul class="search-results">
{{#each searchResults}}
<li class="{{#if selected _id}}selected{{/if}}">
<strong>{{longname}}</strong>: {{#markdown}}{{summary}}{{/markdown}}
</li>
{{else}}
No search results found.
{{/each}}
</ul>
</div>
{{/if}}
</template>

View File

@@ -1,195 +0,0 @@
APICollection = new Mongo.Collection(null);
_.each(DocsData, function (val) {
// XXX only insert things that are actually in the docs
if (val.kind !== "namespace") {
APICollection.insert(val);
}
});
Session.setDefault("searchOpen", false);
Session.setDefault("searchQuery", "");
Session.setDefault("searchResults", []);
Session.setDefault("selectedResultId", null);
// Close search with ESC
$(document).on("keydown", function (event) {
if (event.which === 27) {
Session.set("searchOpen", false);
}
});
$(document).on("keydown", function (event) {
// Don't activate search for special keys or keys with modifiers
if (event.which >= 48 && event.which <= 90 && (!event.ctrlKey) &&
(!event.metaKey) && (!Session.get("searchOpen"))) {
Session.set("searchOpen", true);
Tracker.flush();
$(".search-query").val("");
$(".search-query").focus();
}
});
// scroll $parent to make sure $child is visible
// XXX doesn't work that well, needs improvement
var ensureVisible = function ($child, $parent) {
if (! $child) {
return;
}
// make sure it's inside the visible area
var parentTop = $parent.offset().top;
var parentHeight = $parent.height();
var childTop = $child.offset().top;
var childHeight = $child.height();
// check if bottom is below visible part
if (childTop + childHeight > parentTop + parentHeight) {
var amount = $parent.scrollTop() +
(childTop + childHeight - (parentTop + parentHeight));
$parent.scrollTop(amount);
}
// check if top is above visible section
if (childTop < parentTop) {
$parent.scrollTop($parent.scrollTop() + childTop - parentTop);
}
};
// Whenever selectedResultId changes, make sure the selected element is visible
Tracker.autorun(function () {
if (Session.get("selectedResultId")) {
Tracker.afterFlush(function () {
ensureVisible($(".search-results .selected"), $(".search-results"));
});
}
});
var indexOfByFunction = function (array, truthFunction) {
for (var i = 0; i < array.length; i++) {
if(truthFunction(array[i], i, array)) {
return i;
}
}
return -1;
};
var selectPrevItem = function () {
// find currently selected item
var curIndex = indexOfByFunction(Session.get("searchResults"), function (res) {
return res._id === Session.get("selectedResultId");
});
// select the previous item
if (curIndex > 0) {
Session.set("selectedResultId",
Session.get("searchResults")[curIndex - 1]._id);
}
};
var selectNextItem = function () {
// find currently selected item
var curIndex = indexOfByFunction(Session.get("searchResults"), function (res) {
return res._id === Session.get("selectedResultId");
});
// select the previous item
if (curIndex < Session.get("searchResults").length - 1) {
Session.set("selectedResultId",
Session.get("searchResults")[curIndex + 1]._id);
}
};
Template.search.events({
"keyup input": function (event) {
Session.set("searchQuery", event.target.value);
},
"click .close-search": function () {
Session.set("searchOpen", false);
return false;
},
"keydown": function (event) {
if (event.which === 13) {
Tracker.afterFlush(function () {
if (Session.get("selectedResultId")) {
// XXX make sure this is completely up to date
var selectedName = APICollection.findOne(Session.get("selectedResultId")).longname;
var id = nameToId[selectedName] || selectedName.replace(/[.#]/g, "-");
var url = "#/full/" + id;
window.location.replace(url);
Session.set("searchOpen", false);
}
});
// exit function
return;
}
if (event.which === 38) {
// up
selectPrevItem();
return false;
} else if (event.which === 40) {
// down
selectNextItem();
return false;
}
}
});
// When you have two arrays of search results, use this function to deduplicate
// them
var dedup = function (arrayOfSearchResultsArrays) {
var ids = {};
var dedupedResults = [];
_.each(arrayOfSearchResultsArrays, function (searchResults) {
_.each(searchResults, function (item) {
if (! ids.hasOwnProperty(item._id)) {
ids[item._id] = true;
dedupedResults.push(item);
}
});
});
return dedupedResults;
};
// Only update the search results every 200 ms
var updateSearchResults = _.throttle(function (query) {
var regex = new RegExp(query, "i");
// We do two separate queries so that we can be sure that the name matches
// are above the summary matches, since they are probably more relevant
var nameMatches = APICollection.find({ longname: {$regex: regex}}).fetch();
var summaryMatches = APICollection.find({ summary: {$regex: regex}}).fetch();
var deduplicatedResults = dedup([nameMatches, summaryMatches]);
Session.set("searchResults", deduplicatedResults);
if (deduplicatedResults.length) {
Session.set("selectedResultId", deduplicatedResults[0]._id);
}
}, 200);
// Call updateSearchResults when the query changes
Tracker.autorun(function () {
if (Session.get("searchQuery")) {
updateSearchResults(Session.get("searchQuery"));
} else {
Session.set("searchResults", []);
}
});
Template.search.helpers({
searchResults: function () {
return Session.get("searchResults");
},
searchOpen: function () {
return Session.get("searchOpen");
},
selected: function (_id) {
return _id === Session.get("selectedResultId");
}
});

View File

@@ -1,126 +0,0 @@
#splash_outer {
line-height: 1.3;
font-size: 16px;
.mask {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10;
background: black;
opacity: 0.4;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";
-webkit-transition: opacity .25s;
}
.dialog {
position: fixed;
float: left;
top: 10%;
left: 50%;
width: 450px;
height: 300px;
margin-left: -225px;
z-index: 11;
background: white;
border-width: 5px;
border-color: black;
border-style: solid;
padding: 20px;
.rounded-corners(10px);
}
h1 {
font-size: 3em;
margin: 0;
text-align: center;
border-style: none none solid none;
border-color: black;
border-width: 3px;
margin-bottom: 30px;
line-height: 1;
}
em {
font-style: normal;
font-weight: bold;
}
.hello {
font-weight: bold;
background-color: yellow;
}
ul {
padding-left: 30px;
margin: 30px 0px;
}
li {
margin-bottom: 10px;
}
.beg {
font-size: 1.3em;
padding-bottom: 20px;
}
.submit {
float: right;
.rounded-corners(3px);
padding: 4px;
.buttonify(210);
}
}
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
/*
Handy button code adapted from:
http://forrst.com/posts/Easy_parametric_CSS_buttons_using_LESS_HSLa-sgy
*/
.buttonify (@hue: 150, @sat: 26%, @light: 45%) {
/* vars defined inside mixin so we can pass in the @hue param */
@button_bg: hsla(@hue, @sat, @light, 1);
@button_bg_light: spin(saturate(lighten(@button_bg, 5%), -10%), 22);
@button_border: spin(saturate(lighten(@button_bg, 19%), -10%), 22);
@button_hover: spin(lighten(@button_bg, 3%), 10);
@button_active: spin(saturate(lighten(@button_bg, -15%), 5%), 18);
border-top: 1px solid @button_border;
background: @button_bg;
background: -webkit-gradient(linear, left top, left bottom, from(@button_bg_light), to(@button_bg));
background: -moz-linear-gradient(top, @button_bg_light, @button_bg);
-webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
-moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
box-shadow: rgba(0,0,0,1) 0 1px 0;
text-shadow: rgba(0,0,0,.4) 0 1px 0;
color: white;
font-size: 16px;
text-decoration: none;
vertical-align: middle;
&:hover {
border-top-color: @button_hover;
background: @button_hover;
color: white;
}
&:active {
border-top-color: @button_active;
background: @button_active;
position: relative;
top: 1px;
color: white;
}
}

View File

@@ -1,12 +0,0 @@
if (Meteor.isServer) {
Meteor.AppCache.config({
// Turn off appcache on Safari. Apparently Safari 7's AppCache is totally
// busted. In particular, this fact combined with our "RELOAD_SAFETYBELT"
// strategy causes infinite reloads in Safari at times.
//
// See http://stackoverflow.com/questions/22888945/safari-7-application-cache-does-not-work
safari: false,
// ... and Firefox too. See eg https://github.com/meteor/meteor/issues/3248
firefox: false
});
}

View File

@@ -1,115 +0,0 @@
canonicalizeHtml = function(html) {
var h = html;
// kill IE-specific comments inserted by DomRange
h = h.replace(/<!--IE-->/g, '');
h = h.replace(/<!---->/g, '');
// ignore exact text of comments
h = h.replace(/<!--.*?-->/g, '<!---->');
// make all tags lowercase
h = h.replace(/<\/?(\w+)/g, function(m) {
return m.toLowerCase(); });
// replace whitespace sequences with spaces
h = h.replace(/\s+/g, ' ');
// Trim leading and trailing whitespace
h = h.replace(/^\s+|\s+$/g, '');
// remove whitespace before and after tags
h = h.replace(/\s*(<\/?\w.*?>)\s*/gm, function (m, tag) {
return tag; });
// make tag attributes uniform
h = h.replace(/<(\w+)\s+(.*?)\s*>/g, function(m, tagName, attrs) {
// Drop expando property used by Sizzle (part of jQuery) which leaks into
// attributes in IE8. Note that its value always contains spaces.
attrs = attrs.replace(/sizcache[0-9]+="[^"]*"/g, ' ');
// Similarly for expando properties used by jQuery to track data.
attrs = attrs.replace(/jQuery[0-9]+="[0-9]+"/g, ' ');
// Similarly for expando properties used to DOMBackend to keep
// track of callbacks to fire when an element is removed
attrs = attrs.replace(/\$blaze_teardown_callbacks="[^"]*"/g, ' ');
// And by DOMRange to keep track of the element's DOMRange
attrs = attrs.replace(/\$blaze_range="[^"]*"/g, ' ');
attrs = attrs.replace(/\s*=\s*/g, '=');
attrs = attrs.replace(/^\s+/g, '');
attrs = attrs.replace(/\s+$/g, '');
attrs = attrs.replace(/\s+/g, ' ');
// quote unquoted attribute values, as in `type=checkbox`. This
// will do the wrong thing if there's an `=` in an attribute value.
attrs = attrs.replace(/(\w)=([^'" >/]+)/g, '$1="$2"');
// for the purpose of splitting attributes in a string like 'a="b"
// c="d"', assume they are separated by a single space and values
// are double- or single-quoted, but allow for spaces inside the
// quotes. Split on space following quote.
var attrList = attrs.replace(/(\w)='([^']*)' /g, "$1='$2'\u0000");
attrList = attrList.replace(/(\w)="([^"]*)" /g, '$1="$2"\u0000');
attrList = attrList.split("\u0000");
// put attributes in alphabetical order
attrList.sort();
var tagContents = [tagName];
for(var i=0; i<attrList.length; i++) {
// If there were no attrs, attrList could be `[""]`,
// so skip falsy values.
if (! attrList[i])
continue;
var a = attrList[i].split('=');
// In IE8, attributes whose value is "" appear
// without the '=' sign altogether.
if (a.length < 2)
a.push("");
var key = a[0];
// Drop another expando property used by Sizzle.
if (key === 'sizset')
continue;
var value = a[1];
// make sure the attribute is doubled-quoted
if (value.charAt(0) === '"') {
// Do nothing
} else {
if (value.charAt(0) !== "'") {
// attribute is unquoted. should be unreachable because of
// regex above.
value = '"' + value + '"';
} else {
// attribute is single-quoted. make it double-quoted.
value = value.replace(/\"/g, "&quot;");
}
value = value.replace(/["'`]/g, '"');
}
// Encode quotes and double quotes in the attribute.
var attr = value.slice(1, -1);
attr = attr.replace(/\"/g, "&quot;");
attr = attr.replace(/\'/g, "&quot;");
value = '"' + attr + '"';
// Ensure that styles do not end with a semicolon.
if (key === 'style') {
value = value.replace(/;\"$/, '"');
}
tagContents.push(key+'='+value);
}
return '<'+tagContents.join(' ')+'>';
});
h = h.replace(/</g, "\n<");
h = h.replace(/<!--[^>]*-->/g, "");
return h;
};
var fs = require("fs");
o = fs.readFileSync(process.argv[2], {encoding: "utf8"});
o = canonicalizeHtml(o).replace(/(<\w)/g, "\n$1").replace(/(<\/\w*>)/g, "$1\n");
o = o.replace(/<p>\n<\/p>/gm, "");
console.log(o);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

View File

@@ -1,2 +0,0 @@
User-agent: *
Disallow: