pedalpete
pedalpete

Reputation: 21536

use of 'this' with multiple objects

I'm building a backbone.js app with facebook api and phonegap.

In my User model, I'm trying to attach a listener to see when the user has logged in.

Myapp.Models.User = Backbone.Model.extend({
    initialize: function(){
           FB.Event.subscribe('auth.login', function(response){
            console.log('logged-in event');
            this.get_me();

        });
    },
    get_me: function(){
    console.log('use the api to get user details');
    }
});

of course, when I do this, the this is (I believe) attached to FB, not Myapp. I've tried

var this_user = this;
 FB.Event.subscribe('auth.login', function(response,this_user){
   this_user.get_user();
}

but that still fails.

I've read all sorts of blogs on how to use this, but can't seem to get one that I actually understand when working with multiple objects and how do I refer back to the original object.

Upvotes: 1

Views: 98

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

What you have should work, but note this part:

var this_user = this;
 FB.Event.subscribe('auth.login', function(response,this_user){
   this_user.get_user();
}

The this_user parameter should not be in the anonymous function declaration. That's because Facebook never passes the second parameter in the callback, so it ends up being null; in fact, you should have received a JS error on the this_user.get_user() statement.

var this_user = this;
 FB.Event.subscribe('auth.login', function(response){
   this_user.get_user();
}

Upvotes: 2

alex
alex

Reputation: 490163

var this_user = this;
 FB.Event.subscribe('auth.login', function(response,this_user){
   this_user.get_user();
}

That this_user lookup won't resolve to its parent scope as you have an argument with the same name. Change one or the other.

Upvotes: 1

Related Questions