Search code examples
javascriptbackbone.jsunderscore.jsthis

Backbone 'this' is being set to 'window'


I'm trying to create a Backbone View object. In my initialize code I'm setting a var self = this. And I'm getting a 'self.set is not a function' error. This is because, looking at the debugger, this refers to 'window' when I'm declaring the var self. I have not seen this before.

Can anyone tell why the window is being selected for 'this'

code:

var SongObjectView = Backbone.View.extend({
defaults:{
    el:'#playList',
    template:''
},
initialize:function(){
    var self = this;
    self.set({
        el:'#playList'
    });
    alert('initializing songObjectView template');
    self.template = _.template($('#songObjectView').html());
    self.render();
},
render:function(){
    $(this.el).append(this.template);
}
});

Solution

  • There's no set method in a View object, maybe you wanted setElement?

    If you happen to find this being the window object, it is likely because you've lost context. And there's no reason for self variable assignment, as others pointed out. You can use _.bind, _.bindAll and other ways to pass and set context.

    I tried to clean your example, I hope this helps:

    var SongModel = Backbone.Model.extend({
      defaults: {
        artist: '',
        title: ''
      }
    });
    
    var SongView = Backbone.View.extend({
      template: _.template('Title: <%=title%><br>by <em><%=artist%></em>'),
      initialize:function(){
        this.render();
      },
      render:function(){
        this.$el.append( this.template(this.model.toJSON() ) );
        return this;
      }
    });
    
    var song = new SongModel({
      title: "A Hard Day's Night",
      artist: "The Beatles"
    });
    
    var songView = new SongView({ el: '#playlist', model: song });
    <script src='http://code.jquery.com/jquery.js'></script>
    <script src='http://underscorejs.org/underscore.js'></script>
    <script src='http://backbonejs.org/backbone.js'></script>
    <div id="playlist"></div>