2013-09-16 56 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,即使它通常會更改範圍。