2014-12-08 89 views
0

,我有以下的js代碼,我嘗試登錄該blog_root對象,然後用我的user_root聽與user_root.on任何更改(「child_added」,...)火力地堡匿名用戶身份驗證流程

var root = new Firebase(/*my firebase url*/); 
    var blog_root = root.child("blog"); 
    var user_root; 
    console.log("===="); 
    blog_root.authAnonymously(function(err, authData) { 
     if(err){ 
      console.log("user not authenticated?"+err); 
     }else{ 
      console.log("user authenticated?"+authData.uid); 
      if(authData){ 
       user_root = blog_root.child(authData.uid); 
       user_root.set(authData); 
      } 
     } 
    },{ 
     remember: "sessionOnly" 
    }); 
user_root.on(
    "child_added", //event_name 
    function(snapshot) { 
     //called for each existing element and each new element 
    }  

使用此代碼特別是我的user_root對象顯示爲未定義。我檢查了我的數據,並且匿名用戶已成功添加到blog_root,但似乎無法偵聽user_root上的更改。

我收集的是在我的身份驗證語句中觸發了user_root.on(「child_added」)事件,但這對我來說沒有意義,因爲user_root是在身份驗證語句中初始化的。

任何線索?

回答

3

authAnonymously方法是異步的,回調被調用你首先得到user_root.on('child_added', ...)。嘗試將此聽衆轉入authAnonymously的回調中。

此外,請注意,每當您撥打authAnonymously()時,您正在創建一個新的會話。會話默認會自動保留。要檢查用戶是否已經通過身份驗證,請嘗試ref.getAuth(),如果用戶未經身份驗證(ref.getAuth() === null),則僅調用authAnonymously()

+0

Woot!好吧,現在一切都合情合理。感謝Rob! – ebichuhamster 2014-12-10 13:44:59