[英]Meteor: How to detect if users authenticated
In my app I use accounts-github
. 在我的应用程序中,我使用
accounts-github
。 Works perfect, but I have one problem. 工作完美,但我有一个问题。
In one of my templates I do 在我的一个模板中,我做了
Template.bar.rendered = function () {
if (Meteor.user()) {
// setup stuff
}
}
The problem is that if the user initially is not logged in this code is not executed (thats ok). 问题是如果用户最初没有登录,则不执行此代码(没关系)。 But when the user authenticates this code is not executed again.
但是当用户验证时,此代码不会再次执行。 So the question is how can I listen for this change inside a template (doesn't have to be in inside the
rendered
function!)? 所以问题是如何在模板中监听这个变化(不必在
rendered
函数内部!)?
You could use Deps.autorun
. 你可以使用
Deps.autorun
。 ( http://docs.meteor.com/#deps_autorun ) ( http://docs.meteor.com/#deps_autorun )
Usually Deps.autorun
would run for your whole Meteor app. 通常
Deps.autorun
会运行你的整个Meteor应用程序。 If you want to make it so that it only runs per template you would need to create and stop it in the rendered and destroyed template callbacks 如果你想让它只运行每个模板,你需要在渲染和销毁的模板回调中创建和停止它
eg 例如
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();
}
If you don't need it to run per template (need it to run just once for you app on any template, then you can use the Deps.autorun
on its own, anywhere in your client side code. 如果您不需要它来运行每个模板(需要它在任何模板上为您的app运行一次,那么您可以在客户端代码的任何位置使用
Deps.autorun
。
Meteor.user()
is reactive, it would ensure that the Deps.autorun callback runs again when it changes, so you could theoretically use it to do things when the user logs in or out. Meteor.user()
是被动的,它将确保Deps.autorun回调在它发生变化时再次运行,因此理论上你可以在用户登录或退出时使用它来做事情。
Other alternatives is there is a package on atmosphere that provides login and logout hooks, though they basically would use the Deps.autorun like above to work anyway. 其他选择是有一个大气包提供登录和注销钩子,虽然他们基本上会像上面的Deps.autorun一样工作。 See https://github.com/BenjaminRH/meteor-event-hooks
请参阅https://github.com/BenjaminRH/meteor-event-hooks
My solution for similar problem was to 我对类似问题的解决方案是
Template.bar.rendered
is called Template.bar.rendered
Eg 例如
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.