1

I cant call method() inside FB.api. how can I access method? cant do it this.method(); or method();

var MyLayer = cc.Layer.extend({
   init: function(){
      FB.init({
       ............
      });
      FB.getLoginStatus(function(response) {
         if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  this.method(); // <---- I cant call this here. How can I call method(); ?? Thank!
               });
         }
      });
   },
   method: function(){
      alert("Hello");
   }
});
Jeff Lee
  • 783
  • 9
  • 17

2 Answers2

4

Save a reference to this and use that:

var MyLayer = cc.Layer.extend({
   init: function(){
       var that = this; // Save reference to context
       //.....
       FB.getLoginStatus(function(response) {
           if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  that.method(); // Call method on stored context
               });
           }
        });
    }
});

Alternatively you can bind the callback functions to the context (requires ES5):

var MyLayer = cc.Layer.extend({
   init: function(){
       //.....
       FB.getLoginStatus(function(response) {
           if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  this.method(); // Call method on context
               }.bind(this)); // Bind callback to context
           }
        }.bind(this)); // Bind callback to context
    }
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

Try with:

var MyLayer = cc.Layer.extend({
   init: function(){
      FB.init({});
      FB.getLoginStatus(function(response) {
         if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  MyLayer.method(); 
               });
         }
      });
   },
   method: function(){
      alert("Hello");
   }
});
kayz1
  • 7,260
  • 3
  • 53
  • 56