2013-07-15 34 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的引用。 –