'this' is null after Firebase 3 => on('value'...)

Hello,

Any of you guys ran into this issue with Firebase 3? “this” becomes null when the 'on(‘value’) is invoked.

this.appData.FBGet('users/'+user.uid).on('value', function(snapshot) {
            var objUser = snapshot.val();
            this.events.publish('user:update', objUser);
        });

Thanks for your help.

This is the most complete explanation I’ve seen about how weird “this” is in JavaScript.

2 Likes

I would definitely recommend you to read the article mentioned by @rapropos above, but in short you have to use an arrow function in order to capture the this value of the enclosing context, so that your code works as expected:

    this.appData.FBGet('users/'+user.uid).on('value', (snapshot) => {
        var objUser = snapshot.val();
        this.events.publish('user:update', objUser);
    });

You guys are 100% right. I have no idea how I missed that and it’s one of the main features of the arrow notation. Thank you a lot ! @iignatov @rapropos