![](/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.