You are right that my case isn’t exactly the same as yours, but I think what I did could be extrapolated to your situation. I would use Session.get(‘details1.userId’) and a Session.get(‘details2.usrId’) – or whatever made sense name wise. No need to restrict yourself to just one Session variable.
But what does this actually mean? How does using a global variable to pass an [ID] from one Template to another actually pollute? Especially if I null out the value after the receiver Template is done with the variable.
I don’t understand this as it reads here. Do you mean running the same Template side by side at the same time in the Browser?
How does this solve communication between Templates? Doesn’t using template-scoped variable mean the value does not live outside of the Template? How then would the value escape the template-scope to be pass to the next Template?
I don’t want to make people run in circles, but I think this brings up with what I mean with “Using dynamic variable identifiers only moves the problem”. E.g., how will you tell which template should use which variable identifier
Exact same problem, only instead of “How do I pass around ID’s to templates” it becomes “How do I pass around Session key identifiers to templates” 
My 0.02
Thanks for sharing, this is awesome!
This seems to be a good pattern for parent/child Templates. I’ll definitely look at using this pattern in place of my current method for dealing with parent/child templates.
Also, I think this post is the right place to add this type of Template communication, so thank you again for adding this to the discussion.
I also think there is another kind of Template communication, where one template is not embedded within the other.
In your example, simply by placing menuItems within the Restaurants Template, you created a relationship and scope that can be used for communication.
In your example the ‘child’ Template menuItems will actually render and is in the scope of parent Template Restaurants. This certainly qualifies as Template to Template communication. There are a few patterns for passing data around like this I’ve seen. I really like, and have never seen, your pattern here.
What about if the menuItems Template was not embedded within Restaurants? What if the listing for Restaurants was a table with a hundred Restaurants? Instead of the menu items for that Restaurant displaying within the same screen as the Restaurants list as your example demonstrated, when you clicked on a Restaurant you were swept away to another screen on another route, one where there is a vast array of menu items for that one Restaurant.
In this case there is no parent/child scope – one template knows nothing about the other unless you wire that relationship up. You need a way to communicate, i.e., pass data, from one Template to the next.
You can wire these relationships up in a few ways that I know about. One that you’ve posted about before is to use Iron Router to pass an ‘:_id’ from one Template on a route to another Template on another route. This is a fine pattern, that’s very commonly used.
But there are others, and for good reason. What if you didn’t just want to pass an _id, but an entire Document? That would be more difficult to pass via a Iron Router route I would think – I have not seen an example of this. What is an alternative way to get data from one Template to the next?
You need a variable. Just like you need a variable to pass data from function to function, you can have a variable pass from Template to Template.
As far as I know there are two ‘kinds’ of variables at our disposal. We have scoped, e.g., ReactiveVar and ReactiveDict, and we have un-scoped or global, i.e., Session. Scoped-template variables are just that, scoped to a Template. So the way I see it, they are not the right vehicle for passing data outside of the Template scope. This leaves us with one option, Session.
I no longer have a problem passing a Session variable from one Template to the next to facilitate communication, i.e., data transfer. In fact, is probably the only case, so far, that I see Session as a good choice.
In most cases probably welcomed, true. As long as you can live with the downsides, this is the most straightforward way. But for future reference, it’s not the only way. Especially with upcoming component frameworks.
In the future I’m guessing syntax like this will be more common as well (as soon as the component part of Blaze is mature):
<template name="master">
{{> EmailListComponent id="list"}}
{{> DetailComponent id="detail1" email="list.selectedItem"}}
{{> DetailComponent id="detail2" email="list.selectedItem"}}
</template>
Note the reference to “EmailListComponent” in the other components. This is currently (as far as I know) not possible in plain Blaze.
Hi @aadams,
Could you create and post the simplest example of what you are trying to accomplish? I feel like I could probably come up with a straightforward solution to most problems, and that the real problem is that I don’t have a clear picture of your use-case. Do you have an actual problem you are trying to solve, or is it more like a vague idea that you are wondering about?
What if you didn’t just want to pass an _id, but an entire Document?
This is Spacebars 101. You can pass an object to an inclusion template as a parameter, or by providing it in a data-context using Each or With.
pass the id in the querystring, then use the id to get the document from the collection. data everywhere remember?
I see what you mean, but I’d really like to see an example app of when you’d have two templates which are related enough to be on the same view, but so unrelated that passing data between them is problematic. i.e. can’t the data context be used to bridge things using all the normal ways we have to do that (passing params to inclusion templates, using Each or With, etc.)? I think best for him to post a repo as it seems like neither of us understand exactly what the OP is asking 
Maybe this is where the confusion is,
The Templates in my examples are not in the same view – far from it.
Two different Templates, two different routes, two different screens/views – no relationship other than a route parameter or Session variable.
After reviewing the options in the feedback here on this thread and doing more research, I’ve picked Session variable over route parameter for this purpose – even knowing that choosing this path makes me a scope polluter. 
So what was the use-case? what is the nature of the templates and why are you trying to pass between them? You really have me curious 
Every situation is unique so it’s hard to say what is best.
Maybe a similar case we had is having to “pass” a shopping cart from the addItem page, to the cartSummary page and to the checkout page. Completely different routes/templates. What we do is stick the cart data into a carts collection and retrieve it at each step based on the userId. If they lose their session or switch devices, they get their cart again once they login.
But yeah no reason to be fundamentalist about it. Session is certainly very quick and easy and find for small apps, but you might find it’s usefulness comes with some drawbacks as your application grows. As a rule, whenever I think I need a Session var I try and think of a way to avoid it. Nearly always the non-Session-var approach is cleaner in terms of architecture, maintenance and possible side-effects.
I’m curious of this is applicable? What is the beneficial for this package and couldn’t understand the code examples in the readme.
Hi, I am the creator of that package.
I did it because I am trying to figure out the best way to use Flux and Meteor together.
- Flux is a new architecture created by Facebook for their reactive apps.
- MeteorFlux is a port of the Facebook’s Flux Dispatcher.
There was already an implementation of Flux & Meteor called space-ui. It’s great but for me it tries to do too much stuff. Facebook implementation (and my port) only has a dispatcher because in the end, the dispatcher is all you need. I am in the “the less externals packages you need the better” as well.
Back to the topic, I think you should look for a pattern for your whole app, not only one to pass data between templates.
MVC is great and you can do it with IrounRouter, for example. But that feels like coding a website instead of an app. Like using PHP or Ruby instead of Meteor. The user changes the URL, the controller asks for the data and renders a new view. End.
What you want to do is more like how an app behaves. The user clicks something and other part of the view changes. No url changes. No whole page rendered.
Meteor is great for this, we all know that. But if you don’t use a pattern, you are asking yourself all the time “Where should I put this logic?”, “How do these components communicate?” and things can get messy in a short time.
This is how passing data between templates works in a Flux application:
1- Views are only allowed to dispatch actions. When the user selects a post, this happens:
Template.PostView.events({
'click .post': function(){
Dispatcher.dispatch({
actionType: "USER_HAS_SELECTED_A_POST",
id: $(event.target).attr('data-id')
});
});
2- The Stores are in charge of the App State. They listen to actions and modify the App State in consequence:
// Create the Store. Use the way you prefer. Objects, functions, prototypes,
// classes... it doesn't matter.
PostStore = {};
// Save the App State in local reactive variables.
// If you want it to survive to Hot Code Push use ReactiveDict instead of
// ReactiveVar. Both are MDG packages.
var selectedPostId = new ReactiveVar(false);
// Register to actions and map them to callbacks.
// This "switch" thing looks kind of dirty but it's very flexible.
// It's the way Facebook people do it.
Dispatcher.register(function (payload) {
switch (payload.actionType) {
case "USER_HAS_SELECTED_A_POST":
PostStore.on.postSelected(payload.id);
break;
}
});
// In the Store, you have callback methods.
// They modify the App State when something happens.
// Collections, reactive variables, private variables... whatever you need.
PostStore.onPostSelected = function (id) {
selectedPostId.set(id);
};
// Finally, create methods to retrieve content.
// Views or other interested Stores can use them.
PostStore.getSelectedPost = function() {
return Posts.findOne(selectedPostId.get());
};
3- Back in the View, you just retrieve that value where you need it:
Template.DetailView.helpers({
selectedPost: function () {
return PostStore.getSelectedPost();
}
});
Dispatching actions decouples your app. Now, if you want to do something else when the user selects a post, you don’t need to touch the View. Just register your new Store for that action.
I have created the whole example and uploaded it to github and meteorpad:
http://meteorpad.com/pad/36dwXz9ktQK3SJGgB
I know this is very simple but I am trying to create a complex example to see what problems you can run into. So far so good, but it’s still a work in progress.
This is the thread:
Any feedback or help is welcomed ![]()
By the way, the package @proyb2 mentioned, reactive-dependency, can be used to get rid of globals, use dependency injection or circular dependencies (one object needs another and vice versa).
This is another example of Flux using this package:
As you can see, there aren’t any globals and load order is not a problem.
Stores are just javascript objects, so you don’t need to use Flux to use this package.
Check some of my ideas about this topic in Blaze Components documentation: https://github.com/peerlibrary/meteor-blaze-components#accessing-data-context
Personally, I think there are three ways to pass data around: as data context (when you want to keep the component persisted, to keep some internal change), as component arguments (when you want for it to create), or by traversing components up and down the tree.
All of those are something what you can already do in Blaze. But it is not so clean API to do it.
For me, the most useful thing before making Blaze Components was this helper:
With this you can access fields on parent template instances. And then it is really easy to pass data around with explicit API. So in the parent template instance (or component) you provide methods you want, for an API you want, and then children template instances (or components) can talk to that. I much more like such explicit APIs.
And those methods can even be reactive.
While I have no knowledge on this pattern, I think Reactive Presentation Model could be an interesting additional feature for Meteor by providing an extra layer that wrapped data between logic/model and view.
RPM is just a random term I came up.
@Ben, for now, blaze-component and flow-component don’t tackle component communication issue. Its looks like @mitar is actively evaluating and working on a solution for blaze-component. @manuel s Viewmodel package has an excellent way of handling component communicate (http://viewmodel.meteor.com/#compCommunicationBk) and I think its a good start for other component packages to follow.
I think the key to component communication is
- Api to access instance of template/component
- Api to access instance states for side-effects
I was reading over this post again, and noticed this:
Reading the docs I’m still confused: http://docs.meteor.com/#/full/meteor_subscribe
This excerpt from the docs leads me to think we should have the subscriptions inside the autorun:
If you call Meteor.subscribe within a reactive computation, for example using Tracker.autorun, the subscription will automatically be cancelled when the computation is invalidated or stopped; it’s not necessary to call stop on subscriptions made from inside autorun. However, if the next iteration of your run function subscribes to the same record set (same name and parameters), Meteor is smart enough to skip a wasteful unsubscribe/resubscribe. For example:
Tracker.autorun(function () {
Meteor.subscribe("chat", {room: Session.get("current-room")});
Meteor.subscribe("privateMessages");
});
This subscribes you to the chat messages in the current room and to your private messages. When you change rooms by calling Session.set(“current-room”,
“new-room”), Meteor will subscribe to the new room’s chat messages, unsubscribe from the original room’s chat messages, and continue to stay subscribed to your private messages.
If more than one subscription sends conflicting values for a field (same collection name, document ID, and field name), then the value on the client will be one of the published values, chosen arbitrarily.
I have started using @mitar’s Blaze Components and it has solved my data-passing woes between templates. Honestly, it almost feels like this is how Blaze should’ve functioned from the beginning even though it is a little bit more complicated and somewhat turns so many tables on Blaze (in a good way). this inside your events && (methods || helpers) is not the data context but the template instance and the data context is either this.data() or this.currentData(). So it essentially does away with having to call the awfully verbose Template.instance().
The fact that I can simply call this.reallyFarOffMethodUpTheChainInAParentParentParentTemplate() without having to hot-potato my data down the templates and hope that it’s there is extremely helpful.
Also, no you don’t need to wrap a subscription that takes no parameters inside an autorun and Meteor knowing not to waste an unsubscribe/subscribe is not contingent on it. Wrap them only if they take reactive data sources (Session, ReactiveVar, etc) as parameters.
@aadams Thanks to post amazing topic in advance,
I totally agree all of your opinions, but it seems there’s no perfect solution for now, unfortunately.
Have been using Meteor for an year, I’ve been curious why there’s no perfect data deliver component to carry all fluently.
I think this curious came from mobile programming such as iOS, Android, and they all have their Navigation systems and their own data context delivery containers.
Each screen might have a data context and it could be delivered, and at the first time, Iron Router seems like solving this problem.
But for some reasons, I was tired to use this.
By the way, the way I found is using Blaze.view object.
i.e. in the Template.onCreated methods,
I can access a single ReactiveVar, top of blaze template, something like this.
Blaze.getView(‘with’).dataVar.get() (and even set() available)
I know someone suggested using Blaze to solve this above,
and this would be dangerous when Meteor updates Blaze core in the future,
I thinks this is the only way to inject data when the subscription.ready() in onCreated method for now.
I think someone who wants to bind and prepare all data in one place will understand why we should use this pattern.
I guess now’s a good time to mention React.js’s top-down approach to passing data.
Instead of child templates reaching above for data, it’s the parent’s responsibility to pass things down and the children must work off of that. Not only do they get their data from the top, they also get actions too that they invoke while possibly passing data to it, which is interesting.
The only immediate down-side is that you’d think you would have to pass down things a huge chain, but getChildContext helps solve that problem.
In addition, there’s Flux, Redux and whatever other Ux I may have missed that act like a giant mother-ship of data and actions as a means for interacting between components. Correct me if I’m wrong on these.