2012-10-24 66 views
1

查看“故事”时,我希望自动订阅该故事并在更改页面时更改订阅的故事。流星路线和自动订阅

这就是我得到的:它似乎工作,但多个autosubscribe似乎错了?

route("stories/:storytitle/:storyID", function(storyTitle, storyID) { 
    Session.set('storyID', storyID) 
    Meteor.autosubscribe(function() { 
    var storyID = Session.get('storyID'); 
    if (storyID) 
     Meteor.subscribe("story", Session.get("storyID"), function() { 
     Router.goto('story') 
     }); 
    }); 
}); 

Template.story.data = function() { 
    var storyID = Session.get('storyID'); 
    var story = Stories.findOne({ 
    _id: storyID 
    }) 
    return story; 
}; 

这似乎更符合我在寻找的一般,但有大量的样板。将查询放入路由中似乎也是错误的,而不是仅仅将它放在模板助手中。

route("stories/:storytitle/:storyID", function(storyTitle, storyID) { 
    Session.set('storyID', storyID) 
    var story = Stories.findOne({ 
    _id: storyID 
    }) 
    if (story) 
    Router.goto('story') 
}); 

Meteor.autosubscribe(function() { 
    var storyID = Session.get('storyID'); 
    if (storyID) 
    Meteor.subscribe("story", Session.get("storyID"), function() { 
     Router.goto('story') 
    }); 
}); 

Template.story.data = function() { 
    var storyID = Session.get('storyID'); 
    var story = Stories.findOne({ 
    _id: storyID 
    }) 
    return story; 
}; 

这些都是正确的方法吗?如何在故事中保留自动订阅,并在更改页面时自动更改订阅?

凭直觉我就试试这个:

route("stories/:storytitle/:storyID", function(storyTitle, storyID) { 
    Session.set('storyID', storyID) 
    Router.goto('story') 
}); 

Meteor.autosubscribe(function() { 
    var storyID = Session.get('storyID'); 
    if (storyID) 
    Meteor.subscribe("story", Session.get("storyID"), function() { 
     Router.goto('story') 
    }); 
}); 

这根本不起作用。它会尝试在故事加载之前转到故事路线并引发白屏或错误。

回答

3

第三种方法是正确的,但第二种方法的好处是,如果您想要在其他地方(例如404)发现故事未找到的话。一些注意事项:

  1. 为了避免在第三种方法的错误,只要确保(在您的模板)来处理时findOne不返回任何内容的情况。您应该期望在数据从服务器完全加载之前看到这一点;当数据准备就绪时,模板将重新呈现。

  2. 在第二种情况下在路由中放置查询没有任何问题,但请注意它最初很可能会返回null。您需要将代码封装在被动的上下文中,以便在数据准备就绪时重新执行。你可能想用我的reactive router来实现这一点,或者只是复制技术。

    这样您就不需要在订阅中使用onReady回调。 (实际上你不需要这样做)。

  3. 第一种技术是绝对不会做的:)

  4. 如果你想路由到404,如果这个故事不存在正确的方法,你应该等到数据加载,请参阅:https://github.com/tmeasday/unofficial-meteor-faq#how-do-i-know-when-my-subscription-is-ready-and-not-still-loading

+0

我正在使用你的反应式路由器,这很好,谢谢它:) – Harry

+0

谢谢!我刚刚添加了第四点,我忘了我想说。 –