argument comes from 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.
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
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:
// 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;
});
Accounts.validateLoginAttempt(func) Server
Validate login attempts.
Arguments
- func Function
-
Called whenever a login is attempted (either successful or unsuccessful). A login can be aborted by returning a falsy value or throwing an exception.
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:
- type String
-
The service name, such as "password" or "twitter".
- allowed 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).
- error Exception
-
When
allowed
is false, the exception describing why the login failed. It will be aMeteor.Error
for failures reported to the user (such as invalid password), and can be a another kind of exception for internal errors. - user Object
-
When it is known which user was attempting to login, the Meteor user object. This will always be present for successful logins.
- connection Object
-
The
connection
object the request came in on. SeeMeteor.onConnection
for details. - methodName String
-
The name of the Meteor method being used to login.
- methodArguments Array
-
An array of the arguments passed to the login method.
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;
Accounts.onLogin(func) Anywhere
Register a callback to be called after a login attempt succeeds.
Arguments
- func Function
-
The callback to be called when login is successful.
See description of Accounts.onLoginFailure for details.
Accounts.onLoginFailure(func) Anywhere
Register a callback to be called after a login attempt fails.
Arguments
- func Function
-
The callback to be called after the login has failed.
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
. On the client, no arguments are passed.
Passwords
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 algorithm. This helps protect against embarrassing password leaks if the server's database is compromised.
To add password support to your application, run $ meteor add accounts-password
. You can construct your own user interface using the functions below, or use the accounts-ui
package to include a turn-key user interface for password-based sign-in.
Accounts.createUser(options, [callback]) Anywhere
Create a new user.
Arguments
- callback Function
-
Client only, optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Options
- username String
-
A unique name for this user.
- email String
-
The user's email address.
- password String
-
The user's password. This is not sent in plain text over the wire.
- profile Object
-
The user's profile, typically including the
name
field.
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
— enough information for the user to be able to log in again later. 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
).
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
. 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
.
This function is only used for creating users with passwords. The external service login flows do not use this function.
Accounts.changePassword(oldPassword, newPassword, [callback]) Client
Change the current user's password. Must be logged in.
Arguments
- oldPassword String
-
The user's current password. This is not sent in plain text over the wire.
- newPassword String
-
A new password for the user. This is not sent in plain text over the wire.
- callback Function
-
Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Accounts.forgotPassword(options, [callback]) Client
Request a forgot password email.
Arguments
- callback Function
-
Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
Options
- email String
-
The email address to send a password reset link.
This triggers a call to Accounts.sendResetPasswordEmail
on the server. When the user visits the link in this email, the callback registered with Accounts.onResetPasswordLink
will be called.
If you are using the accounts-ui
package, this is handled automatically. Otherwise, it is your responsiblity to prompt the user for the new password and call resetPassword
.
Accounts.resetPassword(token, newPassword, [callback]) Client
Reset the password for a user using a token received in email. Logs the user in afterwards.
Arguments
- token String
-
The token retrieved from the reset password URL.
- newPassword String
-
A new password for the user. This is not sent in plain text over the wire.
- callback Function
-
Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
This function accepts tokens passed into the callbacks registered with Accounts.onResetPasswordLink
and Accounts.onEnrollmentLink
.
Accounts.setPassword(userId, newPassword, [options]) Server
Forcibly change the password for a user.
Arguments
- userId String
-
The id of the user to update.
- newPassword String
-
A new password for the user.
Options
- logout Object
-
Logout all current connections with this userId (default: true)
Accounts.verifyEmail(token, [callback]) Client
Marks the user's email address as verified. Logs the user in afterwards.
Arguments
- token String
-
The token retrieved from the verification URL.
- callback Function
-
Optional callback. Called with no arguments on success, or with a single
Error
argument on failure.
This function accepts tokens passed into the callback registered with Accounts.onEmailVerificationLink
.
Accounts.sendResetPasswordEmail(userId, [email]) Server
Send an email with a link the user can use to reset their password.
Arguments
- userId String
-
The id of the user to send email to.
- email String
-
Optional. Which address of the user's to send the email to. This address must be in the user's
emails
list. Defaults to the first email in the list.
When the user visits the link in this email, the callback registered with Accounts.onResetPasswordLink
will be called.
To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.sendEnrollmentEmail(userId, [email]) Server
Send an email with a link the user can use to set their initial password.
Arguments
- userId String
-
The id of the user to send email to.
- email String
-
Optional. Which address of the user's to send the email to. This address must be in the user's
emails
list. Defaults to the first email in the list.
When the user visits the link in this email, the callback registered with Accounts.onEnrollmentLink
will be called.
To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.sendVerificationEmail(userId, [email]) Server
Send an email with a link the user can use verify their email address.
Arguments
- userId String
-
The id of the user to send email to.
- email String
-
Optional. Which address of the user's to send the email to. This address must be in the user's
emails
list. Defaults to the first unverified email in the list.
When the user visits the link in this email, the callback registered with Accounts.onEmailVerificationLink
will be called.
To customize the contents of the email, see Accounts.emailTemplates
.
Accounts.onResetPasswordLink(callback) Client
Register a function to call when a reset password link is clicked in an email sent by Accounts.sendResetPasswordEmail
. This function should be called in top-level code, not inside Meteor.startup()
.
Arguments
- callback Function
-
The function to call. It is given two arguments:
token
: A password reset token that can be passed toAccounts.resetPassword
.done
: A function to call when the password reset UI flow is complete. The normal login process is suspended until this function is called, so that the password for user A can be reset even if user B was logged in.
Accounts.onEnrollmentLink(callback) Client
Register a function to call when an account enrollment link is clicked in an email sent by Accounts.sendEnrollmentEmail
. This function should be called in top-level code, not inside Meteor.startup()
.
Arguments
- callback Function
-
The function to call. It is given two arguments:
token
: A password reset token that can be passed toAccounts.resetPassword
to give the newly enrolled account a password.done
: A function to call when the enrollment UI flow is complete. The normal login process is suspended until this function is called, so that user A can be enrolled even if user B was logged in.
Accounts.onEmailVerificationLink(callback) Client
Register a function to call when an email verification link is clicked in an email sent by Accounts.sendVerificationEmail
. This function should be called in top-level code, not inside Meteor.startup()
.
Arguments
- callback Function
-
The function to call. It is given two arguments:
token
: An email verification token that can be passed toAccounts.verifyEmail
.done
: A function to call when the email verification UI flow is complete. The normal login process is suspended until this function is called, so that the user can be notified that they are verifying their email before being logged in.
Accounts.emailTemplates Server
Options to customize emails sent from the Accounts system.
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
: AString
with an RFC5322 From address. By default, the email is sent<EMAIL_ADDRESS>. 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
: AnObject
for custom email headers as described inEmail.send
.resetPassword
: AnObject
with two fields:resetPassword.from
: AFunction
used to override thefrom
address defined by theemailTemplates.from
field.resetPassword.subject
: AFunction
that takes a user object and returns aString
for the subject line of a reset password email.resetPassword.text
: AFunction
that takes a user object and a url, and returns the body text for a reset password email.resetPassword.html
: An optionalFunction
that takes a user object and a url, and returns the body html for a reset password email.
enrollAccount
: Same asresetPassword
, but for initial password setup for new accounts.verifyEmail
: Same asresetPassword
, but for verifying the users email address.
Example:
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin<EMAIL_ADDRESS>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;
};
Templates
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
.
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.
Template.myTemplate.events(eventMap) Client
Specify event handlers for this template.
Arguments
- eventMap Event Map
-
Event handlers to associate with this template.
Declare event handlers for instances of this template. Multiple calls add new event handlers in addition to the existing ones.
See Event Maps for a detailed description of the event map format and how event handling works in Meteor.
Template.myTemplate.helpers(helpers) Client
Specify template helpers available to this template.
Arguments
- helpers Object
-
Dictionary of helper functions by name.
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: function () {
return Session.get("foo");
}
});
Now you can invoke this helper with {{foo}}
in the template defined with <template name="myTemplate">
.
Helpers can accept positional and keyword arguments:
Template.myTemplate.helpers({
displayName: function (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:
{{displayName "John" "Doe" title="President"}}
You can learn more about arguments to helpers in Spacebars Readme.
Under the hood, each helper starts a new 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.myTemplate.onRendered Client
Register a function to be called when an instance of this template is inserted into the DOM.
Arguments
- callback Function
-
A function to be added as a callback.
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 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
which look at its DOM nodes.
Template.myTemplate.onCreated Client
Register a function to be called when an instance of this template is created.
Arguments
- callback Function
-
A function to be added as a callback.
Callbacks added with this method called before your template's logic is evaluated for the first time. Inside a callback, this
is the new template instance 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()
.
Template.myTemplate.onDestroyed Client
Register a function to be called when an instance of this template is removed from the DOM and destroyed.
Arguments
- callback Function
-
A function to be added as a callback.
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 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.
Template instances
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()
.
In addition to the properties and functions described below, you can assign additional properties of your choice to the object. Use the onCreated
and 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
.
template.findAll(selector) Client
Find all elements matching selector
in this template instance.
Arguments
- selector String
-
The CSS selector to match, scoped to the template contents.
template.findAll
returns an array of DOM elements matching selector
.
template.$(selector) Client
Find all elements matching selector
in this template instance, and return them as a JQuery object.
Arguments
- selector String
-
The CSS selector to match, scoped to the template contents.
template.$
returns a jQuery object 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.
template.find(selector) Client
Find one element matching selector
in this template instance.
Arguments
- selector String
-
The CSS selector to match, scoped to the template contents.
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.
template.firstNode Client
The first top-level DOM node in this template instance.
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.
template.lastNode Client
The last top-level DOM node in this template instance.
template.data Client
The data context of this instance's latest invocation.
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.
template.autorun(runFunc) Client
A version of Tracker.autorun that is stopped when the template is destroyed.
Arguments
- runFunc Function
-
The function to run. It receives one argument: a Tracker.Computation object.
You can use this.autorun
from an onCreated
or 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
.
template.subscribe(name, [arg1, arg2...], [callbacks]) Client
A version of Meteor.subscribe that is stopped when the template is destroyed.
Arguments
- name String
-
Name of the subscription. Matches the name of the server's
publish()
call. - arg1, arg2... Any
-
Optional arguments passed to publisher function on server.
- callbacks Function or Object
-
Optional. May include
onStop
andonReady
callbacks. If a function is passed instead of an object, it is interpreted as anonReady
callback.
You can use this.subscribe
from an 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:
Template.notifications.onCreated(function () {
// Use this.subscribe inside onCreated callback
this.subscribe("notifications");
});
<template name="notifications">
{{#if Template.subscriptionsReady}}
<!-- This is displayed when all data is ready. -->
{{#each notifications}}
{{> notification}}
{{/each}}
{{else}}
Loading...
{{/if}}
</template>
Another example where the subscription depends on the data context:
Template.comments.onCreated(function () {
var self = this;
// Use self.subscribe with the data context reactively
self.autorun(function () {
var dataContext = Template.currentData();
self.subscribe("comments", dataContext.postId);
});
});
{{#with post}}
{{> comments postId=_id}}
{{/with}}
template.view Client
The View object for this invocation of the template.
Template.registerHelper(name, function) Client
Defines a helper function which can be used from all templates.
Arguments
- name String
-
The name of the helper function you are defining.
- function Function
-
The helper function itself.
Template.instance() Client
The template instance corresponding to the current template helper, event handler, callback, or autorun. If there isn't one, null
.
Template.currentData() Client
- Inside an
onCreated
,onRendered
, oronDestroyed
callback, returns the data context of the template. - Inside an event handler, returns the data context of the template on which this event handler was defined.
- Inside a helper, returns the data context of the DOM node where the helper was used.
Establishes a reactive dependency on the result.
Template.parentData([numLevels]) Client
Accesses other data contexts that enclose the current data context.
Arguments
- numLevels Integer
-
The number of levels beyond the current data context to look. Defaults to 1.
For example, Template.parentData(0)
is equivalent to Template.currentData()
. Template.parentData(2)
is equivalent to {{../..}}
in a template.
Template.body Client
The template object representing your <body>
tag.
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. 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.
{{> Template.dynamic template=template [data=data] }} Templates
Choose a template to include dynamically, by name.
Arguments
- template String
-
The name of the template to include.
- data Object
-
Optional. The data context in which to include the template.
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.
For example, if there is a template named "foo", {{> Template.dynamic template="foo"}}
is equivalent to {{> foo}}
.
Event Maps
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:
- eventtype
-
Matches a particular type of event, such as 'click'.
- eventtype selector
-
Matches a particular type of event, but only when it appears on an element that matches a certain CSS selector.
- event1, event2
-
To handle more than one type of event with the same function, use a comma-separated list.
The handler function receives two arguments: event
, an object with information about the event, and template
, a template instance 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': function (event) { ... },
// Fires when any element with the 'accept' class is clicked
'click .accept': function (event) { ... },
// Fires when 'accept' is clicked or focused, or a key is pressed
'click .accept, focus .accept, keypress': function (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': function (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:
- type String
-
The event's type, such as "click", "blur" or "keypress".
- target DOM Element
-
The element that originated the event.
- currentTarget 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 oftarget
, and its value changes as the event bubbles. - which Number
-
For mouse events, the number of the mouse button (1=left, 2=middle, 3=right). For key events, a character or key code.
- 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.
- 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.
- 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.
- isPropagationStopped()
-
Returns whether
stopPropagation()
has been called for this event. - isImmediatePropagationStopped()
-
Returns whether
stopImmediatePropagation()
has been called for this event. - isDefaultPrevented()
-
Returns whether
preventDefault()
has been called for this event.
Returning false
from a handler is the same as calling both stopImmediatePropagation
and preventDefault
on the event.
Event types and their uses include:
click
-
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 fireclick
. dblclick
-
Double-click.
focus, blur
-
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. change
-
A checkbox or radio button changes state. For text fields, use
blur
or key events to respond to changes. mouseenter, mouseleave
-
The pointer enters or leaves the bounds of an element. These events do not bubble.
mousedown, mouseup
-
The mouse button is newly down or up.
keydown, keypress, keyup
-
The user presses a keyboard key.
keypress
is most useful for catching typing in text fields, whilekeydown
andkeyup
can be used for arrow keys or modifier keys.
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.
Spacebars
Spacebars is the language used to write Meteor templates. It is inspired by Handlebars. 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.
Blaze
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.
Blaze.render(templateOrView, parentNode, [nextNode], [parentView]) Client
Renders a template or View to DOM nodes and inserts it into the DOM, returning a rendered View which can be passed to Blaze.remove
.
Arguments
- templateOrView Blaze.Template or Blaze.View
-
The template (e.g.
Template.myTemplate
) or View object to render. If a template, a View object is constructed. If a View, it must be an unrendered View, which becomes a rendered View and is returned. - parentNode DOM Node
-
The node that will be the parent of the rendered template. It must be an Element node.
- nextNode DOM Node
-
Optional. If provided, must be a child of parentNode; the template will be inserted before this node. If not provided, the template will be inserted as the last child of parentNode.
- parentView Blaze.View
-
Optional. If provided, it will be set as the rendered View's
parentView
.
When you render a template, the callbacks added with onCreated
are invoked immediately, before evaluating the content of the template. The callbacks added with 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
or the View's parent element is removed by Meteor or jQuery.
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
when the View is no longer needed.
Blaze.renderWithData(templateOrView, data, parentNode, [nextNode], [parentView]) Client
Renders a template or View to DOM nodes with a data context. Otherwise identical to Blaze.render
.
Arguments
- templateOrView Blaze.Template or Blaze.View
-
The template (e.g.
Template.myTemplate
) or View object to render. - data Object or Function
-
The data context to use, or a function returning a data context. If a function is provided, it will be reactively re-run.
- parentNode DOM Node
-
The node that will be the parent of the rendered template. It must be an Element node.
- nextNode DOM Node
-
Optional. If provided, must be a child of parentNode; the template will be inserted before this node. If not provided, the template will be inserted as the last child of parentNode.
- parentView Blaze.View
-
Optional. If provided, it will be set as the rendered View's
parentView
.
Blaze.renderWithData(Template.myTemplate, data)
is essentially the same as Blaze.render(Blaze.With(data, function () { return Template.myTemplate; }))
.
Blaze.remove(renderedView) Client
Removes a rendered View from the DOM, stopping all reactive updates and event listeners on it.
Arguments
- renderedView Blaze.View
-
The return value from
Blaze.render
orBlaze.renderWithData
.
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", 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
, 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.
Blaze.getData([elementOrView]) Client
Returns the current data context, or the data context that was used when rendering a particular DOM element or View from a Meteor template.
Arguments
- elementOrView DOM Element or Blaze.View
-
Optional. An element that was rendered by a Meteor, or a View.
Blaze.toHTML(templateOrView) Client
Renders a template or View to a string of HTML.
Arguments
- templateOrView Blaze.Template or Blaze.View
-
The template (e.g.
Template.myTemplate
) or View object from which to generate HTML.
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 ({{> 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
).
Blaze.toHTMLWithData(templateOrView, data) Client
Renders a template or View to HTML with a data context. Otherwise identical to Blaze.toHTML
.
Arguments
- templateOrView Blaze.Template or Blaze.View
-
The template (e.g.
Template.myTemplate
) or View object from which to generate HTML. - data Object or Function
-
The data context to use, or a function returning a data context.
new Blaze.View([name], renderFunction) Client
Constructor for a View, which represents a reactive region of DOM.
Arguments
- name String
-
Optional. A name for this type of View. See
view.name
. - renderFunction Function
-
A function that returns renderable content. In this function,
this
is bound to the View.
Behind every template or part of a template — a template tag, say, like {{foo}}
or {{#if}}
— 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
on a template, or by accessing template.view
on a template instance.
At the heart of a View is an 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
and is set during View rendering, callbacks, autoruns, and template event handlers. It affects calls such as Template.currentData()
.
The following properties and methods are available on Blaze.View:
- name String
-
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".
- parentView View or null
-
The enclosing View that caused this View to be rendered, if any.
- isCreated Boolean
-
True if this View has been called on to be rendered by
Blaze.render
orBlaze.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 beforeonViewCreated
hooks are called. - isRendered Boolean
-
True if this View has been rendered to DOM by
Blaze.render
or by the rendering of an enclosing View. Conversion to HTML byBlaze.toHTML
doesn't count. Once true, never becomes false. - isDestroyed Boolean
-
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. - renderCount Integer
-
The number of times the View has been rendered, including the current time is the View is in the process of being rendered or re-rendered.
- autorun(runFunc)
-
Like
Tracker.autorun
, except that the autorun is automatically stopped when the View is destroyed, and the current View is always set when runningrunFunc
. There is no relationship to the View's internal autorun or render cycle. InrunFunc
, the View is bound tothis
. - onViewCreated(func)
-
If the View hasn't been created yet, calls
func
when the View is created. Infunc
, the View is bound tothis
.This hook is the basis for the
created
template callback. - onViewReady(func)
-
Calls
func
when the View is rendered and inserted into the DOM, after waiting for the end of flush time. Does not fire if the View is destroyed at any point before it would fire. May fire multiple times (if the View re-renders). Infunc
, the View is bound tothis
.This hook is the basis for the
rendered
template callback. - onViewDestroyed(func)
-
If the View hasn't been destroyed yet, calls
func
when the View is destroyed. A View may be destroyed without ever becoming "ready." Infunc
, the View is bound tothis
.This hook is the basis for the
destroyed
template callback. - firstNode() DOM node
-
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()
andview.lastNode()
, inclusive. - lastNode() DOM node
-
The last node of the View's rendered content.
See
firstNode()
. - template Template
-
For Views created by invoking templates, the original Template object. For example,
Blaze.render(Template.foo).template === Template.foo
. - templateInstance() Template instance
-
For Views created by invoking templates, returns the template instance object for this particular View. For example, in a
created
callback,this.view.templateInstance() === this
.Template instance objects have fields like
data
,firstNode
, andlastNode
which are not reactive and which are also not automatically kept up to date. CallingtemplateInstance()
causes these fields to be updated.
Blaze.currentView Client
The View corresponding to the current template helper, event handler, callback, or autorun. If there isn't one, null
.
The "current view" is used by Template.currentData()
and Template.instance()
to determine the contextually relevant data context and template instance.
Blaze.getView([element]) Client
Gets either the current View, or the View enclosing the given DOM element.
Arguments
- element DOM Element
-
Optional. If specified, the View enclosing
element
is returned.
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.With(data, contentFunc) Client
Constructs a View that renders content with a data context.
Arguments
- data Object or Function
-
An object to use as the data context, or a function returning such an object. If a function is provided, it will be reactively re-run.
- contentFunc Function
-
A Function that returns renderable content.
Returns an unrendered View object you can pass to Blaze.render
.
Unlike {{#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.
Blaze.If(conditionFunc, contentFunc, [elseFunc]) Client
Constructs a View that renders content conditionally.
Arguments
- conditionFunc Function
-
A function to reactively re-run. Whether the result is truthy or falsy determines whether
contentFunc
orelseFunc
is shown. An empty array is considered falsy. - contentFunc Function
-
A Function that returns renderable content.
- elseFunc Function
-
Optional. A Function that returns renderable content. If no
elseFunc
is supplied, no content is shown in the "else" case.
Returns an unrendered View object you can pass to Blaze.render
.
Matches the behavior of {{#if}}
in templates.
Blaze.Unless(conditionFunc, contentFunc, [elseFunc]) Client
An inverted Blaze.If
.
Arguments
- conditionFunc Function
-
A function to reactively re-run. If the result is falsy,
contentFunc
is shown, otherwiseelseFunc
is shown. An empty array is considered falsy. - contentFunc Function
-
A Function that returns renderable content.
- elseFunc Function
-
Optional. A Function that returns renderable content. If no
elseFunc
is supplied, no content is shown in the "else" case.
Returns an unrendered View object you can pass to Blaze.render
.
Matches the behavior of {{#unless}}
in templates.
Blaze.Each(argFunc, contentFunc, [elseFunc]) Client
Constructs a View that renders contentFunc
for each item in a sequence.
Arguments
- argFunc Function
-
A function to reactively re-run. The function may return a Cursor, an array, null, or undefined.
- contentFunc Function
-
A Function that returns renderable content.
- elseFunc Function
-
Optional. A Function that returns renderable content to display in the case when there are no items to display.
Returns an unrendered View object you can pass to Blaze.render
.
Matches the behavior of {{#each}}
in templates.
new Blaze.Template([viewName], renderFunction) Client
Constructor for a Template, which is used to construct Views with particular name and content.
Arguments
- viewName String
-
Optional. A name for Views constructed by this Template. See
view.name
. - renderFunction Function
-
A function that returns renderable content. This function is used as the
renderFunction
for Views constructed by this 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, the following fields and methods are present on template objects:
- viewName String
-
Same as the constructor argument.
- renderFunction Function
-
Same as the constructor argument.
- 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{{> foo}}
wherefoo
resolves to a Template object.constructView()
constructs a View usingviewName
andrenderFunction
as constructor arguments, and then configures it as a template View, setting upview.template
,view.templateInstance()
, event maps, and so on.
Blaze.isTemplate(value) Client
Returns true if value
is a template object like Template.myTemplate
.
Arguments
- value Any
-
The value to test.
Renderable Content
A value is renderable content if it is one of the following:
- A template object like
Template.myTemplate
- An unrendered View object, like the return value of
Blaze.With
null
orundefined
Internally, renderable content includes objects representing HTML tags as well, but these objects are not yet part of the officially-supported, public API.
Timers
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
.
Meteor.setTimeout(func, delay) Anywhere
Call a function in the future after waiting for a specified delay.
Arguments
- func Function
-
The function to run
- delay Number
-
Number of milliseconds to wait before calling function
Returns a handle that can be used by Meteor.clearTimeout
.
Meteor.setInterval(func, delay) Anywhere
Call a function repeatedly, with a time delay between calls.
Arguments
- func Function
-
The function to run
- delay Number
-
Number of milliseconds to wait between each function call.
Returns a handle that can be used by Meteor.clearInterval
.
Meteor.clearTimeout(id) Anywhere
Cancel a function call scheduled by Meteor.setTimeout
.
Arguments
- id Number
-
The handle returned by
Meteor.setTimeout
Meteor.clearInterval(id) Anywhere
Cancel a repeating function call scheduled by Meteor.setInterval
.
Arguments
- id Number
-
The handle returned by
Meteor.setInterval
Tracker
Meteor has a simple dependency tracking system which allows it to automatically rerun templates and other computations whenever Session
variables, database queries, and other data sources change.
Unlike most other systems, you don't have to manually declare these dependencies — 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
useful, while more advanced facilities such as Tracker.Dependency
and onInvalidate
callbacks are intended primarily for package authors implementing new reactive data sources.
To learn more about how Tracker works and to explore advanced ways to use it, visit the Tracker chapter in the Meteor Manual, which describes it in complete detail.
Tracker.autorun(runFunc) Client
Run a function now and rerun it later whenever its dependencies change. Returns a Computation object that can be used to stop or observe the rerunning.
Arguments
- runFunc Function
-
The function to run. It receives one argument: the Computation object that will be returned.
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
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
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.
Tracker.flush() Client
Process all reactive updates immediately and ensure that all invalidated computations are rerun.
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 — 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
are called after processing outstanding invalidations.
It is illegal to call flush
from inside a flush
or from a running computation.
The Meteor Manual describes the motivation for the flush cycle and the guarantees made by Tracker.flush
and Tracker.afterFlush
.
Tracker.nonreactive(func) Client
Run a function without tracking dependencies.
Arguments
- func Function
-
A function to call immediately.
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.
Tracker.active Client
True if there is a current computation, meaning that dependencies on reactive data sources will be tracked and potentially cause the current computation to be rerun.
This value is useful for data source implementations to determine whether they are being accessed reactively or not.
Tracker.currentComputation Client
The current computation, or null
if there isn't one. The current computation is the Tracker.Computation
object created by the innermost active call to Tracker.autorun
, and it's the computation that gains dependencies when reactive data sources are accessed.
It's very rare to need to access currentComputation
directly. The current computation is used implicitly by Tracker.active
(which tests whether there is one), dependency.depend()
(which registers that it depends on a dependency), and Tracker.onInvalidate
(which registers a callback with it).
Tracker.onInvalidate(callback) Client
Registers a new onInvalidate
callback on the current computation (which must exist), to be called immediately when the current computation is invalidated or stopped.
Arguments
- callback Function
-
A callback function that will be invoked as
func(c)
, wherec
is the computation on which the callback is registered.
See computation
.onInvalidate
for more details.
Tracker.afterFlush(callback) Client
Schedules a function to be called during the next flush, or later in the current flush if one is in progress, after all invalidated computations have been rerun. The function will be run once and not on subsequent flushes unless afterFlush
is called again.
Arguments
- callback Function
-
A function to call at flush time.
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.
Tracker.Computation
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
. Use 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
) 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
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();
});
}
computation.stop() Client
Prevents this computation from rerunning.
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.
Nested computations are stopped automatically when their enclosing computation is rerun.
computation.invalidate() Client
Invalidates this computation so that it will be rerun.
Invalidating a computation marks it to be rerun at flush time, 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
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.
computation.onInvalidate(callback) Client
Registers callback
to run when this computation is next invalidated, or runs it immediately if the computation is already invalidated. The callback is run exactly once and not upon future invalidations unless onInvalidate
is called again after the computation becomes valid again.
Arguments
- callback Function
-
Function to be called on invalidation. Receives one argument, the computation that was invalidated.
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
from onInvalidate
.
computation.stopped Client
True if this computation has been stopped.
computation.invalidated Client
True if this computation has been invalidated (and not yet rerun), or if it has been stopped.
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.
computation.firstRun Client
True during the initial run of the computation at the time Tracker.autorun
is called, and false on subsequent reruns and at other times.
This property is a convenience to support the common pattern where a computation has logic specific to the first run.
Tracker.Dependency
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
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 Meteor Manual to learn how to create a reactive data source using Tracker.Dependency.
dependency.changed() Client
Invalidate all dependent computations immediately and remove them as dependents.
dependency.depend([fromComputation]) Client
Declares that the current computation (or fromComputation
if given) depends on dependency
. The computation will be invalidated the next time dependency
changes.
If there is no current computation and depend()
is called with no arguments, it does nothing and returns false.
Returns true if the computation is a new dependent of dependency
rather than an existing one.
Arguments
- fromComputation Tracker.Computation
-
An optional computation declared to depend on
dependency
instead of the current computation.
dep.depend()
is used in reactive data source implementations to record the fact that dep
is being accessed from the current computation.
dependency.hasDependents() Client
True if this Dependency has one or more dependent Computations, which would be invalidated if this Dependency were to change.
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.
ReactiveVar
To use ReactiveVar
, add the reactive-var
package to your project with $ meteor add reactive-var
.
new ReactiveVar(initialValue, [equalsFunc]) Client
Constructor for a ReactiveVar, which represents a single reactive variable.
Arguments
- initialValue Any
-
The initial value to set.
equalsFunc
is ignored when setting the initial value. - equalsFunc Function
-
Optional. A function of two arguments, called on the old value and the new value whenever the ReactiveVar is set. If it returns true, no set is performed. If omitted, the default
equalsFunc
returns true if its arguments are===
and are of type number, boolean, string, undefined, or null.
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 — which is sometimes a reason for using one — 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.
reactiveVar.get() Client
Returns the current value of the ReactiveVar, establishing a reactive dependency.
reactiveVar.set(newValue) Client
Sets the current value of the ReactiveVar, invalidating the Computations that called get
if newValue
is different from the old value.
Arguments
- newValue Any
EJSON
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 ofEJSON.newBinary
) - User-defined types (see
EJSON.addType
. For example,Mongo.ObjectID
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":<PHONE_NUMBER>553},
"b": {"$binary": "c3VyZS4="}
}
Meteor supports all built-in EJSON data types in publishers, method arguments and results, Mongo databases, and Session
variables.
EJSON.parse(str) Anywhere
Parse a string into an EJSON value. Throws an error if the string is not valid EJSON.
Arguments
- str String
-
A string to parse into an EJSON value.
EJSON.stringify(val, [options]) Anywhere
Serialize a value to a string.
For EJSON values, the serialization fully represents the value. For non-EJSON values, serializes the same way as JSON.stringify
.
Arguments
- val EJSON-able Object
-
A value to stringify.
Options
- indent Boolean, Integer, or String
-
Indents objects and arrays for easy readability. When
true
, indents by 2 spaces; when an integer, indents by that number of spaces; and when a string, uses the string as the indentation pattern. - canonical Boolean
-
When
true
, stringifies keys in an object in sorted order.
EJSON.fromJSONValue(val) Anywhere
Deserialize an EJSON value from its plain JSON representation.
Arguments
- val JSON-compatible Object
-
A value to deserialize into EJSON.
EJSON.toJSONValue(val) Anywhere
Serialize an EJSON-compatible value into its plain JSON representation.
Arguments
- val EJSON-able Object
-
A value to serialize to plain JSON.
EJSON.equals(a, b, [options]) Anywhere
Return true if a
and b
are equal to each other. Return false otherwise. Uses the equals
method on a
if present, otherwise performs a deep comparison.
Arguments
Options
- keyOrderSensitive Boolean
-
Compare in key sensitive order, if supported by the JavaScript implementation. For example,
{a: 1, b: 2}
is equal to{b: 2, a: 1}
only whenkeyOrderSensitive
isfalse
. The default isfalse
.
EJSON.clone(val) Anywhere
Return a deep copy of val
.
Arguments
- val EJSON-able Object
-
A value to copy.
EJSON.newBinary Anywhere
Allocate a new buffer of binary data that EJSON can serialize.
Arguments
- size Number
-
The number of bytes of binary data to allocate.
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
.
EJSON.isBinary(x) Anywhere
Returns true if x
is a buffer of binary data, as returned from EJSON.newBinary
.
Arguments
- x Object
-
The variable to check.
EJSON.addType(name, factory) Anywhere
Add a custom datatype to EJSON.
Arguments
- name String
-
A tag for your custom type; must be unique among custom data types defined in your project, and must match the result of your type's
typeName
method. - factory Function
-
A function that deserializes a JSON-compatible value into an instance of your type. This should match the serialization performed by your type's
toJSONValue
method.
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.
- storing your type client-side in Minimongo.
- allowing your type in
Session
variables.
Instances of your type must implement typeName
and toJSONValue
methods, and may implement clone
and equals
methods if the default implementations are not sufficient.
customType.typeName() Anywhere
Return the tag used to identify this type. This must match the tag used to register this type with EJSON.addType
.
customType.toJSONValue() Anywhere
Serialize this instance into a JSON-compatible value.
For example, the toJSONValue
method for Mongo.ObjectID
could be:
function () {
return this.toHexString();
};
customType.clone() Anywhere
Return a value r
such that this.equals(r)
is true, and modifications to r
do not affect this
and vice versa.
If your type does not have a clone
method, EJSON.clone
will use toJSONValue
and the factory instead.
customType.equals(other) Anywhere
Return true
if other
has a value equal to this
; false
otherwise.
Arguments
- other Object
-
Another object to compare this to.
The equals
method should define an 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
andb
:a.equals(b)
if and only ifb.equals(a)
. - Transitivity - for any three instances
a
,b
, andc
:a.equals(b)
andb.equals(c)
impliesa.equals(c)
.
If your type does not have an equals
method, EJSON.equals
will compare the result of calling toJSONValue
instead.
HTTP
HTTP
provides an HTTP request API on the client and server. To use these functions, add the HTTP package to your project with $ meteor add http
.
HTTP.call(method, url, [options], [asyncCallback]) Anywhere
Perform an outbound HTTP request.
Arguments
- method String
-
The HTTP method to use, such as "
GET
", "POST
", or "HEAD
". - url String
-
The URL to retrieve.
- asyncCallback Function
-
Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.
Options
- content String
-
String to use as the HTTP request body.
- data Object
-
JSON-able object to stringify and use as the HTTP request body. Overwrites
content
. - query String
-
Query string to go in the URL. Overwrites any query string in
url
. - params Object
-
Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If
content
ordata
is specified,params
will always be placed in the URL. - auth String
-
HTTP basic authentication string of the form
"username:password"
- headers Object
-
Dictionary of strings, headers to add to the HTTP request.
- timeout Number
-
Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.
- followRedirects Boolean
-
If
true
, transparently follow HTTP redirects. Cannot be set tofalse
on the client. Defaulttrue
. - npmRequestOptions Object
-
On the server,
HTTP.call
is implemented by using the npmrequest
module. Any options in this object will be passed directly to therequest
invocation.
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()
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:
- statusCode Number
- Numeric HTTP result status code, or
null
on error. - content String
- The body of the HTTP response as a string.
- data Object or
null
- If the response headers indicate JSON content, this contains the body of the document parsed as a JSON object.
- headers Object
- A dictionary of HTTP headers from the response.
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);
}
});
HTTP.get(url, [callOptions], [asyncCallback]) Anywhere
Send an HTTP GET
request. Equivalent to calling HTTP.call
with "GET" as the first argument.
Arguments
- url String
-
The URL to which the request should be sent.
- callOptions Object
-
Options passed on to
HTTP.call
. - asyncCallback Function
-
Callback that is called when the request is completed. Required on the client.
HTTP.post(url, [callOptions], [asyncCallback]) Anywhere
Send an HTTP POST
request. Equivalent to calling HTTP.call
with "POST" as the first argument.
Arguments
- url String
-
The URL to which the request should be sent.
- callOptions Object
-
Options passed on to
HTTP.call
. - asyncCallback Function
-
Callback that is called when the request is completed. Required on the client.
HTTP.put(url, [callOptions], [asyncCallback]) Anywhere
Send an HTTP PUT
request. Equivalent to calling HTTP.call
with "PUT" as the first argument.
Arguments
- url String
-
The URL to which the request should be sent.
- callOptions Object
-
Options passed on to
HTTP.call
. - asyncCallback Function
-
Callback that is called when the request is completed. Required on the client.
HTTP.del(url, [callOptions], [asyncCallback]) Anywhere
Send an HTTP DELETE
request. Equivalent to calling HTTP.call
with "DELETE" as the first argument. (Named del
to avoid conflic with the Javascript keyword delete
)
Arguments
- url String
-
The URL to which the request should be sent.
- callOptions Object
-
Options passed on to
HTTP.call
. - asyncCallback Function
-
Callback that is called when the request is completed. Required on the client.
The email
package allows sending email from a Meteor app. To use it, add the package to your project with $ 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/
. For apps deployed with meteor deploy
, MAIL_URL
defaults to an account (provided by Mailgun) which allows apps to send up to 200 emails per day; you may override this default by assigning to process.env.MAIL_URL
before your first call to Email.send
.
If MAIL_URL
is not set (eg, when running your application locally), Email.send
outputs the message to standard output instead.
Email.send(options) Server
Send an email. Throws an Error
on failure to contact mail server or if mail server returns an error. All fields should match RFC5322 specification.
Options
- from String
-
"From:" address (required)
- to, cc, bcc, replyTo String or Array of Strings
-
"To:", "Cc:", "Bcc:", and "Reply-To:" addresses
- subject String
-
"Subject:" line
- text, html String
-
Mail body (in plain text and/or HTML)
- headers Object
-
Dictionary of custom headers
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',
<EMAIL_ADDRESS><EMAIL_ADDRESS>'Hello from Meteor!',
'This is a test of Email.send.');
Assets
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.
Assets.getText(assetPath, [asyncCallback]) Server
Retrieve the contents of the static server asset as a UTF8-encoded string.
Arguments
- assetPath String
-
The path of the asset, relative to the application's
private
subdirectory. - asyncCallback Function
-
Optional callback, which is called asynchronously with the error or result after the function is complete. If not provided, the function runs synchronously.
Assets.getBinary(assetPath, [asyncCallback]) Server
Retrieve the contents of the static server asset as an EJSON Binary.
Arguments
- assetPath String
-
The path of the asset, relative to the application's
private
subdirectory. - asyncCallback Function
-
Optional callback, which is called asynchronously with the error or result after the function is complete. If not provided, the function runs synchronously.
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');
Package.js
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
. 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.
Package Description
Provide basic package information with Package.describe(options)
. To publish a package, you must define summary
and version
.
Package.describe(options) package.js
Provide basic package information.
Options
- summary String
-
A concise 1-2 sentence description of the package, required for publication.
- version String
-
The (extended) semver version for your package. Additionally, Meteor allows a wrap number: a positive integer that follows the version number. If you are porting another package that uses semver versioning, you may want to use the original version, postfixed with
_wrapnumber
. For example,1.2.3_1
or2.4.5-rc1_4
. Wrap numbers sort after the original numbers:1.2.3
<1.2.3_1
<1.2.3_2
<1.2.4-rc.0
. If no version is specified, this field defaults to0.0.0
. If you want to publish your package to the package server, you must specify a version. - name String
-
Optional name override. By default, the package name comes from the name of its directory.
- git String
-
Optional Git URL to the source repository.
- documentation String
-
Optional Filepath to documentation. Set to 'README.md' by default. Set this to null to submit no documentation.
Package Definition
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.
Package.onUse(func) package.js
Define package dependencies and expose package methods.
Arguments
- func Function
-
A function that takes in the package control
api
object, which keeps track of dependencies and exports.
api.versionsFrom(meteorRelease) package.js
Use versions of core packages from a release. Unless provided, all packages will default to the versions released along with meteorRelease
. This will save you from having to figure out the exact versions of the core packages you want to use. For example, if the newest release of meteor is<EMAIL_ADDRESS>and it includes<EMAIL_ADDRESS>, you can write<EMAIL_ADDRESS>in your package, and when you later write api.use('jquery')
, it will be equivalent to<EMAIL_ADDRESS>. You may specify an array of multiple releases, in which case the default value for constraints will be the "or" of the versions from each release<EMAIL_ADDRESS><EMAIL_ADDRESS>may cause api.use('jquery')
to be interpreted as<EMAIL_ADDRESS>|| 2.0.0')
.
Arguments
- meteorRelease String or Array of Strings
-
Specification of a release: track@version. Just 'version' (e.g.
"0.9.0"
) is sufficient if using the default release trackMETEOR
.
api.use(packageNames, [architecture], [options]) package.js
Depend on package packagename
.
Arguments
- packageNames String or Array of Strings
-
Packages being depended on. Package names may be suffixed with an @version tag.
In general, you must specify a package's version (e.g.,
<EMAIL_ADDRESS>to use version 1.0.0 or a higher compatible version (ex: 1.0.1, 1.5.0, etc.) of theaccounts
package). If you are sourcing core packages from a Meteor release withversionsFrom
, you may leave off version names for core packages. You may also specify constraints, such<EMAIL_ADDRESS>(this package demandsmy:forms
at1.0.0
exactly<EMAIL_ADDRESS>|| =2.0.1
(my:forms
at1.x.y
, or exactly2.0.1
). - architecture String
-
If you only use the package on the server (or the client), you can pass in the second argument (e.g.,
'server'
,'client'
,'web.browser'
,'web.cordova'
) to specify what architecture the package is used with.
Options
- weak Boolean
-
Establish a weak dependency on a package. If package A has a weak dependency on package B, it means that including A in an app does not force B to be included too — but, if B is included or by another package, then B will load before A. You can use this to make packages that optionally integrate with or enhance other packages if those packages are present. When you weakly depend on a package you don't see its exports. You can detect if the possibly-present weakly-depended-on package is there by seeing if
Package.foo
exists, and get its exports from the same place. - unordered Boolean
-
It's okay to load this dependency after your package. (In general, dependencies specified by
api.use
are loaded before your package.) You can use this option to break circular dependencies.
api.imply(packageSpecs) package.js
Give users of this package access to another package (by passing in the string packagename
) or a collection of packages (by passing in an array of strings [packagename1
, packagename2
]
Arguments
- packageSpecs String or Array of Strings
-
Name of a package, or array of package names, with an optional @version component for each.
api.export(exportedObject, [architecture]) package.js
Export package-level variables in your package. The specified variables (declared without var
in the source code) will be available to packages that use this package.
Arguments
- exportedObject String
-
Name of the object.
- architecture String
-
If you only want to export the object on the server (or the client), you can pass in the second argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the export is used with.
api.addFiles(filename, [architecture]) package.js
Specify the source code for your package.
Arguments
- filename String or Array of Strings
-
Name of the source file, or array of strings of source file names.
- architecture String
-
If you only want to export the file on the server (or the client), you can pass in the second argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the file is used with.
Unit Tests
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.
Package.onTest(func) package.js
Define dependencies and expose package methods for unit tests.
Arguments
- func Function
-
A function that takes in the package control 'api' object, which keeps track of dependencies and exports.
External Packages and Plugins
Meteor packages can include NPM packages and Cordova plugins by using Npm.depends
and Cordova.depends
in the package.js
file.
Npm.depends(dependencies) package.js
Specify which NPM packages your Meteor package depends on.
Arguments
- dependencies Object
-
An object where the keys are package names and the values are version numbers in string form. You can only depend on exact versions of NPM packages. Example:
Npm.depends({moment: "2.8.3"});
Npm.require(name) Server
Require a package that was specified using Npm.depends()
.
Arguments
- name String
-
The name of the package to require.
Cordova.depends(dependencies) package.js
Specify which Cordova / PhoneGap plugins your Meteor package depends on.
Plugins are installed from plugins.cordova.io, so the plugins and versions specified must exist there. Alternatively, the version can be replaced with a GitHub tarball URL as described in the Cordova / PhoneGap page of the Meteor wiki on GitHub.
Arguments
- dependencies Object
-
An object where the keys are plugin names and the values are version numbers or GitHub tarball URLs in string form. Example:
Cordova.depends({ "org.apache.cordova.camera": "0.3.0" });
Alternatively, with a GitHub URL:
Cordova.depends({ "org.apache.cordova.camera": "https://github.com/apache/cordova-plugin-camera/tarball/d84b875c" });
Package.registerBuildPlugin([options]) package.js
Define a build plugin. A build plugin extends the build process for apps and packages that use this package. For example, the coffeescript
package uses a build plugin to compile CoffeeScript source files into JavaScript.
Options
- name String
-
A cosmetic name, must be unique in the package.
- use String or Array of Strings
-
Meteor packages that this plugin uses, independent of the packages specified in api.onUse.
- sources Array of Strings
-
The source files that make up the build plugin, independent from api.addFiles.
- npmDependencies Object
-
An object where the keys are NPM package names, and the keys are the version numbers of required NPM packages, just like in Npm.depends.
Plugin.registerSourceHandler(fileExtension, handler) Build Plugin
Inside a build plugin source file specified in Package.registerBuildPlugin, add a handler to compile files with a certain file extension.
Arguments
- fileExtension String
-
The file extension that this plugin should handle, without the first dot. Examples:
"coffee"
,"coffee.md"
. - handler Function
-
A function that takes one argument, a CompileStep object.
Documentation for CompileStep is available on the GitHub Wiki.
Mobile Config File
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.
// 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<EMAIL_ADDRESS>website: 'http://example.com'
});
// Set up resources such as icons and launch screens.
App.icons({
'iphone': 'icons/icon-60.png',
'iphone_2x'<EMAIL_ADDRESS>// ... more screen sizes and platforms ...
});
App.launchScreens({
'iphone': 'splash/Default~iphone.png',
'iphone_2x'<EMAIL_ADDRESS>// ... more screen sizes and platforms ...
});
// Set PhoneGap/Cordova preferences
App.setPreference('BackgroundColor', '0xff0000ff');
App.setPreference('HideKeyboardFormAccessoryBar', true);
// Pass preferences for a particular PhoneGap/Cordova plugin
App.configurePlugin('com.phonegap.plugins.facebookconnect', {
APP_ID: '1234567890',
API_KEY: 'supersecretapikey'
});
App.info(options)
Set your mobile app's core configuration information.
Options
- id, version, name, description, author, email, website String
-
Each of the options correspond to a key in the app's core configuration as described in the PhoneGap documentation.
App.setPreference(name, value)
Add a preference for your build as described in the PhoneGap documentation.
Arguments
- name String
-
A preference name supported by Phonegap's
config.xml
. - value String
-
The value for that preference.
App.accessRule(domainRule, [options])
Set a new access rule based on origin domain for your app. By default your application has a limited list of servers it can contact. Use this method to extend this list.
Default access rules:
tel:*
,geo:*
,mailto:*
,sms:*
,market:*
are allowed and launch externally (phone app, or an email client on Android)gap:*
,cdv:*
,file:
are allowed (protocols required to access local file-system)http://meteor.local/*
is allowed (a domain Meteor uses to access app's assets)- The domain of the server passed to the build process (or local ip address in the development mode) is used to be able to contact the Meteor app server.
Read more about domain patterns in Cordova docs.
Starting with Meteor 1.0.4 access rule for all domains and protocols (<access origin="*"/>
) is no longer set by default due to certain kind of possible attacks.
Arguments
- domainRule String
-
The pattern defining affected domains or URLs.
Options
- launchExternal Boolean
-
Set to true if the matching URL should be handled externally (e.g. phone app or email client on Android).
App.configurePlugin(pluginName, config)
Set the build-time configuration for a Phonegap plugin.
Arguments
- pluginName String
-
The identifier of the plugin you want to configure.
- config Object
-
A set of key-value pairs which will be passed at build-time to configure the specified plugin.
App.icons(icons)
Set the icons for your mobile app.
Arguments
- icons Object
-
An Object where the keys are different devices and screen sizes, and values are image paths relative to the project root directory.
Valid key values:
iphone
iphone_2x
iphone_3x
ipad
ipad_2x
android_ldpi
android_mdpi
android_hdpi
android_xhdpi
App.launchScreens(launchScreens)
Set the launch screen images for your mobile app.
Arguments
- launchScreens Object
-
A dictionary where keys are different devices, screen sizes, and orientations, and the values are image paths relative to the project root directory.
For Android, launch screen images should be special "Nine-patch" image files that specify how they should be stretched. See the Android docs.
Valid key values:
iphone
iphone_2x
iphone5
iphone6
iphone6p_portrait
iphone6p_landscape
ipad_portrait
ipad_portrait_2x
ipad_landscape
ipad_landscape_2x
android_ldpi_portrait
android_ldpi_landscape
android_mdpi_portrait
android_mdpi_landscape
android_hdpi_portrait
android_hdpi_landscape
android_xhdpi_portrait
android_xhdpi_landscape
Packages
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:
$ meteor add <package_name>
and removed with:
$ meteor remove <package_name>
Some of the packages that Meteor Development Group maintains include:
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. 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 in the Meteor wiki.
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 {{> 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 {{> 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 {{> loginButtons}}
, use Accounts.ui.config
.
accounts-ui
also includes modal popup dialogs to handle links from sendResetPasswordEmail
, sendVerificationEmail
, and sendEnrollmentEmail
. These do not have to be manually placed in HTML: they are automatically activated when the URLs are loaded.
audit-argument-checks
This package causes Meteor to require that all arguments passed to methods and publish functions are check
ed. 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.
coffeescript
CoffeeScript 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). 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 calledshare
is visible in CoffeeScript code and is shared across all.coffee
files in the same package. So, you can writeshare.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.
jquery
jQuery 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:
less
LESS 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.
If you want to @import
a file, give it the extension .import.less
to prevent Meteor from processing it independently.
markdown
This package lets you use Markdown in your templates. It's easy: just put your markdown inside {{#markdown}} ... {{/markdown}}
tags. You can still use all of the usual Meteor template features inside a Markdown block, such as {{#each}}
, and you still get reactivity.
Example:
{{#markdown}}I am using __markdown__.{{/markdown}}
outputs
<p>I am using <strong>markdown</strong>.</p>
oauth-encryption
Encrypts sensitive account credential information stored in the database. See packages/oauth-encryption/README.md for details.
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).
- Random.id([n])
-
Returns a unique identifier, such as
"Jjwjg6gouWLXhMGKW"
, that is likely to be unique in the whole world. The optional argumentn
specifies the length of the identifier in characters and defaults to 17. - 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. UseRandom.secret
for security-critical secrets that are intended for machine, rather than human, consumption. - Random.fraction()
-
Returns a number between 0 and 1, like
Math.random
. - Random.choice(arrayOrString)
-
Returns a random element of the given array or string.
- Random.hexString(n)
-
Returns a random string of
n
hexadecimal digits.
underscore
Underscore 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.
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.
We have slightly modified the way Underscore differentiates between objects and arrays in collection functions. 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). 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
.
webapp
The webapp
package is what lets your Meteor app serve content to a web browser. It is included in the meteor-platform
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 API for handling requests through WebApp.connectHandlers
. Here's an example that will let you handle a specific URL:
// 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 object with some extra properties. This argument can be used to get information about the incoming request.
- res - a Node.js 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.
Command line
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.
meteor help
Get help on meteor command line usage. Running meteor help
by itself will list the common meteor commands. Running meteor help command
will print detailed help about the command.
meteor run
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 localhost:3000. 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.
meteor debug
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 debugger
keyword, 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
.
meteor create name
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.
meteor deploy site
Deploy the project in your current directory to Meteor's servers.
You can deploy to any available name under meteor.com
without any additional configuration, for example, myapp.meteor.com
. If you deploy to a custom domain, such as myapp.mydomain.com
, then you'll need to make sure the DNS for that domain is configured to point at origin.meteor.com
.
The first time you deploy an app you'll be prompted for an email address — follow the link in your email to finish setting up your account.
Once you have your account you can log in and log out from the command line, check your username with meteor whoami
, and run meteor authorized
to give other Meteor developers permissions to deploy your app and access its database and logs.
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.
If you use a domain name other than meteor.com
you must ensure that the name resolves to origin.meteor.com
. If you want a top-level domain like myapp.com, you'll need a DNS A record, matching the IP address of origin.meteor.com.
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
.
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.
meteor logs site
Retrieves the server logs for the named Meteor application.
Meteor redirects the output of console.log()
in your server code into a logging server. meteor logs
displays those logs. In client code, the output of console.log()
is available in your web browser's inspector, just like any other client-side JavaScript.
meteor update
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<EMAIL_ADDRESS>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 change (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 nessesary.
meteor add package
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<EMAIL_ADDRESS>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<EMAIL_ADDRESS>. You can also 'or' constraints together: for example, meteor add<EMAIL_ADDRESS>|| =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
.
meteor remove package
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
.
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
.
meteor list
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.
meteor add-platform platform
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 platform' to run on the platform, and 'meteor build' to build the Meteor project for every added platform.
meteor remove-platform platform
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'.
meteor list-platforms
Lists all of the platforms that have been explicitly added to your project.
meteor mongo
Open a MongoDB shell on your local development database, so that you can view or manipulate it directly.
For now, you must already have your application running locally with meteor run
. This will be easier in the future.
meteor reset
Reset the current project to a fresh state. Removes the local mongo database.
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 db.collection.find()
to inspect your data.
For now, you can not run this while a development server is running. Quit all running meteor applications before running this.
meteor build
Package this project up for deployment. The output is a directory with several build artifacts:
- a tarball that includes everything necessary to run the application server (see `README` in the tarball for details)
- an unassigned `apk` bundle and a project source if Android is targetted as a mobile platform
- a directory with an Xcode project source if iOS is targetted as a mobile platform
You can use the application server bundle to host a Meteor application on your own server, instead of deploying to Meteor's servers. You will have to deal with logging, monitoring, backups, load-balancing, etc, all of which we handle for you if you use meteor deploy
.
Unassigned 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.
meteor search
Searches for Meteor packages and releases, whose names contain the specified regular expression.
meteor show
Shows more information about a specific package or release: name, summary, the usernames of its maintainers, and, if specified, its homepage and git URL.
meteor publish
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 Development Accounts 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.
meteor publish-for-arch
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. The servers for meteor deploy
run 64-bit Linux.
meteor publish-release
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
.
meteor test-packages
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.
meteor admin
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.