1

我不能在 FB.api 中调用 method()。我怎样才能访问方法?不能这样做 this.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");
   }
});
4

2 回答 2

4

保存一个引用this并使用它:

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
               });
           }
        });
    }
});

或者,您可以bind回调函数到上下文(需要 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
    }
});
于 2013-05-12T07:48:14.977 回答
0

尝试:

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");
   }
});
于 2013-05-12T07:51:36.530 回答