0

下面是我正在玩的示例代码:

var myRootRef = new Firebase('https://url.firebaseIO.com/');

var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
    if (error) {
        // an error occurred while attempting login
        console.log(error);
    } else if (user) {
        // user authenticated with Firebase
        console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
    } else {
        // user is logged out

        console.log('logged out!');
        login();
    }
});


function login(){
    var email = "something@gmail.com";
    var password = "123";

    authClient.login('password', {
        email: email,
        password: password,
        rememberMe: true
    });
}

我回来的错误是:无法调用未定义的方法“登录”

authClient 似乎总是为空?我究竟做错了什么?

4

2 回答 2

2

这里authClient似乎不错。我认为 login() 函数的范围有问题。试试这个

    var myRootRef = new Firebase('https://url.firebaseIO.com/');
    var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
        if (error) {
            // an error occurred while attempting login
            console.log(error);
        } else if (user) {
            // user authenticated with Firebase
            console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
        } else {
            // user is logged out

            console.log('logged out!');

        var email = "something@gmail.com";
        var password = "123";

        this.login('password', {
            email: email,
            password: password,
            rememberMe: true
        });
        }
    });
于 2013-05-28T10:19:14.917 回答
1

当您最初调用 时new FirebaseAuthClient,它将使用当前登录状态调用回调(例如,当调用它时,用户可能已经登录)。此回调发生在new FirebaseAuthClient返回之前,这意味着authClient尚未分配。

您不需要authClient.login在回调中移动 your ,尽管这样可以正常工作。您只需要注意这样一个事实,即第一次发出此回调可能是在分配之前。

例如,您可以setTimeout在调用周围使用 a 来确保首先设置变量:

var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
    if (error) {
        // an error occurred while attempting login
        console.log(error);
    } else if (user) {
        // user authenticated with Firebase
        console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
    } else {
        // user is logged out
        console.log('not logged in yet or logged out again!');
        setTimeout(login, 1);
    }
});
于 2013-05-30T20:50:47.160 回答