Compare Meteor.subcribe() Vs this.subscribe() [Meteor + Blaze]

荒凉一梦 提交于 2019-12-23 15:41:43

问题


I have two pages/Template,

  1. Dashboard (contains some User specific data as well).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!