簡體   English   中英

Meteor.js:如何在限制訂閱的同時動態路由?

[英]Meteor.js: How to dynamically route while limiting subscription?

如果存在某些內容,我會嘗試將其路由到另一頁;如果不存在,則會嘗試將其路由至另一頁。 但是,我不想訂閱整個集合(約數千個),因為我認為這會影響性能。 我該怎么做呢?

我嘗試過類似的操作,但是由於某種原因,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來檢查它在服務器端,但是它不起作用,也不理想(路由器正在等待服務器調用..)。 是否有“正確”的方法來做到這一點?

之所以得到這種“閃爍”效果,可能是因為您的路由器被實現為反應性的(我不確定這是否是正確的策略BTW),並且由於您使用的是Items.findOne ,因此該方法會使當前Meteor.subscribe請求的數據到達Items集合后立即進行計算。

另外,請注意,活動計算中的每個訂閱都會在重新計算后自動取消。 但是,正如文檔中所聲稱的那樣(請參閱此處 ), 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM