0

I have a simple music app written using backbone.js. I'm having trouble with the code below in one of my models:

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

The first self.get works fine. The second self.get in the stationHasLicense callback, however, throws the error. I'm using var self = this all over other areas of my app to keep scope, but I'm not sure why this instance is failing.

Danny
  • 3,615
  • 6
  • 43
  • 58

1 Answers1

2

Try to use bind from underscore to bind this context when exec the func.

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

Can find more discussions on the topics on that=this or self=this:

Community
  • 1
  • 1
Ming Chan
  • 1,938
  • 11
  • 21
  • Thanks for the answer and links. For whatever reason, if I use anything except for "self" in the example above, it works. No idea why...it really makes zero sense. – Danny Jul 23 '13 at 20:40
  • You may be stepping over on 'window.self' object. Added a refer to the self, window, and window.self. – Ming Chan Jul 24 '13 at 00:49