![](/img/trans.png)
[英]Test Meteor server method calling in client code with authenticated users
[英]Meteor: How to detect if users authenticated
在我的应用程序中,我使用accounts-github
。 工作完美,但我有一个问题。
在我的一个模板中,我做了
Template.bar.rendered = function () {
if (Meteor.user()) {
// setup stuff
}
}
问题是如果用户最初没有登录,则不执行此代码(没关系)。 但是当用户验证时,此代码不会再次执行。 所以问题是如何在模板中监听这个变化(不必在rendered
函数内部!)?
你可以使用Deps.autorun
。 ( http://docs.meteor.com/#deps_autorun )
通常Deps.autorun
会运行你的整个Meteor应用程序。 如果你想让它只运行每个模板,你需要在渲染和销毁的模板回调中创建和停止它
例如
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();
}
如果您不需要它来运行每个模板(需要它在任何模板上为您的app运行一次,那么您可以在客户端代码的任何位置使用Deps.autorun
。
Meteor.user()
是被动的,它将确保Deps.autorun回调在它发生变化时再次运行,因此理论上你可以在用户登录或退出时使用它来做事情。
其他选择是有一个大气包提供登录和注销钩子,虽然他们基本上会像上面的Deps.autorun一样工作。 请参阅https://github.com/BenjaminRH/meteor-event-hooks
我对类似问题的解决方案是
Template.bar.rendered
例如
Template.bar.events({
'click .loginButton' : function() {
if( Meteor.call.Login( username, pw ) )
{
$('#bar').html( Meteor.render( Template.bar ));
//jQuery is optional
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.