问题
I have two pages/Template,
- Dashboard (contains some User specific data as well).
- Users.
I am using Meteor 1.5 with Blaze Template. Landing Page is Dashboard. I am using the common subscription for Collection Users
in both Templates.
Scenario 1
When I use Meteor.subscribe('Users')
in Dashboard's template.onCreated()
and go to Users page, I see some already subscribed data coming back from Dashboard's subscription.
CODE:
Template.DashBoard.onCreated(function(){
Meteor.subscribe('Users');
});
Template.Users.onCreated(function(){
Meteor.subscribe('Users');
});
Scenario 2
When I use this.subscribe('Users')
in Dashboard's template.onCreated()
and go to Users page, I get a Fresh Subscription happening here and no data carry over from Dashboard's subscription.
CODE:
Template.DashBoard.onCreated(function(){
this.subscribe('Users');
});
Template.Users.onCreated(function(){
this.subscribe('Users');
});
Question
What is the difference between Meteor.subscribe('Users')
and this.subscribe('Users')
? What can be the impact of using this.subscribe('Users')
?
回答1:
As explained in Meteor documentation, this.subscribe
within Template code will be automatically unsubscribed when the template instance is destroyed.
Whereas Meteor.subscribe
needs to be explicitly unsubscribed if you want it to.
The decision to use one or the other depends on your app structure. If you are sure the data is relevant only for a given template, then use template scoped subscription, i.e. this.subscribe
.
If the data is used across several pages, either use the "global" form, or scoped at a higher template level (one that persists through your pages, e.g. on layout).
来源:https://stackoverflow.com/questions/49708151/compare-meteor-subcribe-vs-this-subscribe-meteor-blaze