Reputation: 31
I am writing a simple meteor app using meteor-router. My issue is that the router is aware of request parameters, but templates are not. So I've wound up with conventions such as this:
Meteor.Router.add({'/projects/:id', function(id) {
Session.set('currentProjectId', id);
return 'project';
}
Template.project.project = function() {
return Projects.findOne(Session.get('currentProjectId'));
}
Is there a cleaner way to get the current request ID param at the Template level, to avoid all these session variables?
Upvotes: 3
Views: 631
Reputation: 2961
The session object is a global (singletone) registry. There are lots of reasons not use them (Just google for "why (singletone, global objects, registry pattern) (is|are) bad".
In Meteor the situation is a bit more special. The Session object is a very easy way to store variables reactively. That's the only reason why you're not using a global variable in your application. Assuming you wouldn't need the reactivity - would you make it a global variable? Probably not.
You're mis-using the session to get the contents of a variable from one place in your code to another one (being a invisible "mystical bridge" of contents between two other ways not related objects). This is neither the "Meteor" way nor clean use at all (referring to the search results above). It's just a easy, dirty possibility.
Cleaner approach
How to avoid this: create your own reactive variable. Meteor provides all the means for it, and it's really easy to do so:
(function () {
var currentProject;
var currentProjectDependency = new Deps.Dependency();
Meteor.Router.add({'/projects/:id', function(id) {
currentProject = id;
currentProjectDependency.changed();
return 'project';
}
Template.project.project = function() {
Deps.depend(currentProjectDependency);
return Projects.findOne(currentProject);
}
}());
Now we don't use the session to store the information but have reactivity as well. Furthermore we don't pollute the global space. Note that with the latest release Meteor adds the closures automatically.
This example can be extend to more complex use-cases with reactivity spanning over several objects (e.g. a controller). Have a look at my navigation package as bit more complex example.
Reasons to use Session
So why does the Session exist at all? Two reasons:
For simplicity. Meteor tries hard to be beginner's friendly. The approach I described is a bit more complex due to the understanding of reactivity and architecture. Most projects are small enough to not care about this.
But even larger projects can use session: for storing information across page reloads you could not recover else. In my opinion this is the only reason to use session at all. The session content is "persisted" across page reloads from code pushes. If this considered bad then? No. Because only one object relies on the contents of the session. Note that this does not apply to your example as you can recover the information easily.
Upvotes: 5