The Session in Meteor

Meteor is a reactive framework. What this means is that as data changes, things in your application change without you having to explicitly do anything. The current state of the user’s application is completely contained in the URL that they are looking at (and the database). But in many cases, you’ll need to store some ephemeral state that is only relevant to the current user’s version of the application (for example, whether an element is shown or hidden). The Session is a convenient way to do this.

The Session is a global reactive data store. It’s global in the sense of a global singleton object: there’s one session, and it’s accessible everywhere. Global variables are usually seen as a bad thing, but in this case the session can be used as a central communication bus for different parts of the application.The Session is a global reactive data store. It’s global in the sense of a global singleton object: there’s one session, and it’s accessible everywhere. Global variables are usually seen as a bad thing, but in this case the session can be used as a central communication bus for different parts of the application.

The Session is available anywhere on the client as the Session object. To set a session value, you can call:

[cc lang=”javascript”]

Session.set(‘pageTitle’, ‘A different title’);

[/cc]

You can read the data back out again with Session.get(‘mySessionProperty’); This is a reactive data source, which means that if you were to put it in a helper, you would see the helper’s output change reactively as the Session variable is changed. To try this, add the following code to the layout template:

[cc lang=”html”]

[/cc]

[cc lang=”html”]
Template.layout.helpers({
pageTitle: function() { return Session.get(‘pageTitle’); }
});
[/cc]

Now type in the browser’s console:

[cc lang=”javascript”]
Session.set(‘pageTitle’, ‘A brand new title’);
[/cc]

The Session is globally available, so such changes can be made anywhere in the application.


Posted

in

, , ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *