流星:如何检测用户是否经过身份验证

Meteor: How to detect if users authenticated

本文关键字:用户 是否 经过 身份验证 检测 何检测 流星      更新时间:2023-09-26

在我的应用程序中,我使用accounts-github。工作完美,但我有一个问题。

在我的一个模板中,我做了

Template.bar.rendered = function () {
    if (Meteor.user()) {
        // setup stuff
    }
}

问题是,如果用户最初没有登录,则不会执行此代码(没关系)。但是,当用户进行身份验证时,不会再次执行此代码。所以问题是我如何在模板中侦听这种变化(不一定要在rendered函数中!)?

您可以使用Deps.autorun。(http://docs.meteor.com/deps_autorun)

通常Deps.autorun会为你的整个流星应用程序运行。如果你想让它只运行每个模板,你需要在渲染和销毁模板回调中创建和停止它

var loginRun;
Template.bar.rendered = function() {
    loginRun = Deps.autorun(function() {
        if(Meteor.user()) {
            //Stuff to run when logged in
        }
    });
}
Template.bar.destroyed = function() {
    loginRun.stop();
}

如果你不需要它在每个模板上运行(只需要它在任何模板上为你的应用运行一次),那么你可以在客户端代码的任何地方单独使用Deps.autorun

Meteor.user()是反应性的,它将确保Deps。Autorun回调会在它改变时再次运行,所以理论上你可以在用户登录或退出时使用它来做一些事情。

其他替代方案是在atmosphere上有一个提供登录和注销钩子的包,尽管它们基本上会使用Deps。Autorun像上面一样工作。见https://github.com/BenjaminRH/meteor-event-hooks

对于类似的问题,我的解决方案是

  1. 将事件附加到发生登录的模板
  2. 如果登录成功,则重新渲染模板,因此Template.bar.rendered被称为

Template.bar.events({ 
   'click .loginButton' : function() {
    if( Meteor.call.Login( username, pw ) )
    {
        $('#bar').html( Meteor.render( Template.bar ));
        //jQuery is optional
    }
});