【问题标题】:Meteor.js: How to dynamically route while limiting subscription?Meteor.js:如何在限制订阅的同时动态路由?
【发布时间】:2013-10-20 22:48:59
【问题描述】:

如果存在某些内容,我会尝试路由到一个页面,如果不存在,则尝试路由到另一个页面。但是,我不想订阅整个集合(〜数千),因为我认为它会影响性能。我该怎么做?

我尝试了类似的方法,但由于某种原因,Meteor 在页面加载时会两次遍历路由器代码,并在重定向到项目页面之前短暂闪烁错误页面,我不希望这种情况发生。

这是我所拥有的:

router.coffee

to: (id)->
  Meteor.subscribe 'item', id
  item = Items.findOne id
  if item
    # if the item exists, then redirect to it
    Session.set 'currentItemId', id
    'itemPage'
  else
    # if not, then redirect to the sorry page
    'sorryPage'

publications.coffee

Meteor.publish 'item', (id)->
  return Items.find({_id: id})

订阅整个集合会影响性能,对吗?有没有更简单的方法来检查集合中的存在而不订阅它?我试图做一个 Meteor.call 来检查它的服务器端,但它没有工作并且不理想(路由器等待服务器调用..)。有没有“正确”的方法来做到这一点?

【问题讨论】:

标签: collections meteor router subscription


【解决方案1】:

你得到这种“闪烁”效果的原因可能是因为你的路由器被实现为反应式(我不确定这是否是一个正确的策略顺便说一句)并且因为你使用的是Items.findOne,所以这个方法只要Meteor.subscribe 请求的数据到达Items 集合,当前计算就会失效。

另外,请注意,一旦重新计算计算,活动计算中的每个订阅都会自动取消。但是,正如文档中所声称的那样(看here)Meteor 应该足够聪明,可以检测到您何时订阅了同一数据集两次,因此这不应该有任何副作用。

如果我是你,我会考虑将我的路由器逻辑更改为这样的:

Session.set('currentItemId', id);
var status = Session.get('currentItemStatus');    
if (status === 'ready')
    return 'itemPage';
if (status === 'missing')
    return 'sorryPage';
return 'loadingPage'; // probably status === 'loading'

然后,我会在项目的其他地方做:

Deps.autorun(function () {
    Session.set('currentItemStatus', 'loading');  
    Meteor.subscribe('item', Session.get('currentItemId'), function () {
        // onReady callback
        var item = Items.findOne({_id:id});
        if (item)
            Session.set('currentItemStatus', 'ready');
        else
            Session.set('currentItemStatus', 'missing');
    });
});

请注意,如果currentItemId 没有改变,Deps.autorun 定义的计算不会失效,因此不会向用户显示不必要的loadingPage。

【讨论】:

  • 我最终切换到 Iron-router,但这是我提出的问题的解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多