Session
provides a global object on the client that you can use to
store an arbitrary set of key-value pairs. Use it to store things like
the currently selected item in a list.
What’s special about Session
is that it’s reactive. If
you call Session.get
('currentList')
from inside a template, the template will automatically be rerendered
whenever Session.set
('currentList', x)
is called.
To add Session
to your application, run this command in your terminal:
1 | meteor add session |
Session.set(key, value)
Set a variable in the session. Notify any listeners that the value
has changed (eg: redraw templates, and rerun any
Tracker.autorun
computations, that called
Session.get
on this key
.)
Arguments
- key String
-
The key to set, eg,
selectedItem
- value EJSON-able Object or undefined
-
The new value for
key
Example:
1 | Tracker.autorun(() => { |
Session.set
can also be called with an object of keys and values, which is
equivalent to calling Session.set
individually on each key/value pair.
1 | Session.set({ |
Session.setDefault(key, value)
Set a variable in the session if it hasn't been set before.
Otherwise works exactly the same as Session.set
.
Arguments
- key String
-
The key to set, eg,
selectedItem
- value EJSON-able Object or undefined
-
The new value for
key
This is useful in initialization code, to avoid re-initializing a session variable every time a new version of your app is loaded.
Get the value of a session variable. If inside a reactive
computation, invalidate the computation the next time the
value of the variable is changed by Session.set
. This
returns a clone of the session value, so if it's an object or an array,
mutating the returned value has no effect on the value stored in the
session.
Arguments
- key String
-
The name of the session variable to return
Example:
1 | <!-- main.html --> |
1 | // main.js |
Session.equals(key, value)
Test if a session variable is equal to a value. If inside a reactive computation, invalidate the computation the next time the variable changes to or from the value.
Arguments
- key String
-
The name of the session variable to test
- value String, Number, Boolean, null, or undefined
-
The value to test against
If value is a scalar, then these two expressions do the same thing:
1 | Session.get('key') === value |
…but the second one is always better. It triggers fewer invalidations (template redraws), making your program more efficient.
Example:
1 | <template name="postsView"> |
1 | Template.postsView.helpers({ |
Using Session.equals here means that when the user clicks on an item and changes the selection, only the newly selected and the newly unselected items are re-rendered.
If Session.get had been used instead of Session.equals, then when the selection changed, all the items would be re-rendered.
For object and array session values, you cannot use Session.equals
; instead,
you need to use the underscore
package and write
_.isEqual(Session.get(key), value)
.