2013-09-16 140 views
0

我知道问题出在哪里,但不知道解决此问题的最佳选择是什么。我有一个回调,我无法从它访问this。我不想在范围之外有任何变量来引用它。我可以通过this作为参数吗?将此传递给回调

var myModule = Module.create({ 

      init: function() { 
       ws.subscribe('/topic/notifications', this._wsNotifications, headers); 
      }, 

      refresh: function() { 
      }, 

      _wsNotifications: function (message) { 
       this.refresh(); //Error: 'this' is undefined because it's a callback 
      } 
     }); 
+0

当然你可以,你试过吗? – tymeJV

+0

为什么你不想要一个超出回调范围的变量来保存对此的引用?这是一个完全可以接受的做法。 – DoctorMick

+1

使用'myModule.refresh(); ' – davidkonrad

回答

2

一种方式做

ws.subscribe('/topic/notifications', this._wsNotifications.bind(this), headers); 

或缓存this给一个变量。

var myModule = Module.create({ 
     self : this, 
     init: function() { 
      ws.subscribe('/topic/notifications', this._wsNotifications, headers); 
     }, 

     refresh: function() { 
     }, 

     _wsNotifications: function (message) { 
      self.refresh(); //Error: 'this' is undefined because it's a callback 
     } 
    }); 
+0

绑定是否支持IE7? – RuntimeException

+0

@RuntimeException。不可以。您可以添加文件中提到的垫片。 – PSL

+0

检查文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – PSL

2

你可以利用的EcmaScript的bind functionFunction.prototype.bind的。现在

init: function() { 
      ws.subscribe('/topic/notifications', this._wsNotifications.bind(this), headers); 
     }, 

,内_wsNotificationsthis将把你绑定了的对象。你可以,这是从源头当你指定回调使用function.bind解决

2

试试这个。

var myModule = Module.create({ 

     var self = this; 

     init: function() { 
      ws.subscribe('/topic/notifications', this._wsNotifications, headers); 
     }, 

     refresh: function() { 
     }, 

     _wsNotifications: function (message) { 
      self.refresh(); //Error: 'this' is undefined because it's a callback 
     } 

    }); 

    return interactions; 
}); 

说明在创建和使用self变量,而不是this变量。使用此方法将保留this,即使它通常会更改范围。