【问题标题】:Selecting active Meteor Subscriptions选择活跃的 Meteor 订阅
【发布时间】:2015-12-25 19:37:41
【问题描述】:

我正在阅读“发现流星”一书,但遇到了一个难以解决的问题。我的问题是,Meteor 如何知道如何激活要订阅的出版物?

这是我的 Publications.js 服务器端

Meteor.publish('posts', function(limit){
    return Posts.find({}, {sort: {submitted: -1}, limit: limit});
});

Meteor.publish('newPosts', function(limit) {
  return Posts.find({}, {sort: {submitted: -1}, limit: limit});
});

Meteor.publish('bestPosts', function(limit) {
  return Posts.find({}, {sort: {votes: -1, submitted: -1}, limit: limit});
});

Meteor.publish('singlePost', function(id) {
  return id && Posts.find(id);
});


Meteor.publish('comments', function(postId) {
  return Comments.find({postId: postId});
});

Meteor.publish('notifications', function() {
  return Notifications.find({userId: this.userId});
});

然后是位于 main.js 中的订阅

newPostsHandle = Meteor.subscribeWithPagination('newPosts', 10);
bestPostsHandle = Meteor.subscribeWithPagination('bestPosts', 10);

postHandle = Meteor.subscribeWithPagination('posts', 10);

Deps.autorun(function() {  
  Meteor.subscribe('comments', Session.get('currentPostId'));
})

Meteor.subscribe('notifications');

那么流星如何知道哪些订阅是必要的?无论我在应用程序的哪个位置,我都订阅了每个订阅吗?我认为路由器在起作用,但我不知道我是否清楚地看到路由器在做什么来管理订阅?

【问题讨论】:

  • 你删除包autopublish了吗?

标签: javascript meteor


【解决方案1】:

Meteor 激活您告诉它的订阅。所以订阅如下:

Meteor.subscribe('posts');

客户端开始运行后将立即订阅posts,并始终保持订阅打开。另一方面,如果你有一个 autorun 喜欢:

Tracker.autorun(function() {
  Meteor.subscribe('comments', Session.get('currentPostId'));
});

订阅将在客户端启动时再次激活,但只要currentPostId 会话变量更新,它就会重新运行。请注意,一个常见的习惯用法是用户一登录就发起一些订阅。例如:

Tracker.autorun(function() {
  if (Meteor.userId())
    Meteor.subscribe('friends');
});

在上述所有情况下,订阅的激活与用户在应用中的位置无关。使用 Iron-router 的 waitOn 挂钩来激活与当前路由相关的订阅是非常常见的。例如:

Router.map(function () {
  this.route('dashboard', {
    waitOn: function () {
      return Meteor.subscribe('news');
    }
  });
});

每当用户导航到dashboard 路由时,他也会订阅news。当他离开时,订阅将停止(有一些警告),新的订阅将根据路由器的配置方式开始。旁注:Subscriptions Manager 是对在路由之间导航时不断启动和停止订阅问题的有趣优化。

最后,我要指出的是,混合使用全局订阅和特定路由订阅是完全合理的。随意混合搭配以适合您的应用。

【讨论】:

  • 谢谢大卫。也许有点跑题了,但是一次激活所有这些订阅是否合理?您认为客户端上存在过多数据的原因是什么?
  • 很遗憾,这个问题没有准确的答案。在我们的主应用程序中,我们可能同时有 10-15 个订阅/用户(全局和基于路由的混合)。订阅痛苦的一阶近似值将基于订阅的文档数量及其修改频率。可能会为活跃订阅的数量支付一些罚款,但我在实践中没有注意到这一点。就像软件工程中的一切一样,我不会尽早优化。尝试做最有意义的事情,然后measure 你在生产中的表现。
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2017-07-22
相关资源
最近更新 更多