2013-07-15 35 views
0

我有一個使用backbone.js編寫的簡單音樂應用程序。我在下面的代碼中遇到了一些問題:Backbonejs範圍問題,變量變得未定義

MyApp.Models.Program = Backbone.Model.extend({ 
    toPlaylist: function(options, callback) { 
     console.log("Converting program to playlist"); 

     var self = this; 
     console.log(self.get('name')); 
     this.stationHasLicense(function (licensedStation) { 
      console.log(self.get('name')); // Uncaught TypeError: Cannot call method 'get' of undefined 
      // bunch of other logic 
     }); 
    }, 
}); 

第一個self.get可以正常工作。然而,stationHasLicense回調中的第二個self.get引發錯誤。我使用var self =這在我的應用程序的其他區域保持範圍,但我不知道爲什麼這個實例失敗。

回答

2

嘗試使用來自underscore的綁定綁定上下文時,exec函數。

MyApp.Models.Program = Backbone.Model.extend({ 
    toPlaylist: function(options, callback) { 
     console.log("Converting program to playlist"); 

     var self = this; 
     console.log(self.get('name')); 
     this.stationHasLicense(_.bind(function (licensedStation) { 
      console.log(this.get('name')); 
      // bunch of other logic 
     }, this)); 
    }, 
}); 

可以找到話題上=更多的討論,這或自=此:

+0

感謝答案和鏈接。無論出於何種原因,如果我在上面的例子中使用除「self」之外的任何內容,它都可以使用。不知道爲什麼......它確實毫無意義。 – Danny

+0

您可能正在'window.self'對象上執行操作。增加了對自我,窗口和window.self的引用。 –