Backbone 'this' 正在设置为 'window'

Backbone 'this' is being set to 'window'

我正在尝试创建一个 Backbone 视图对象。在我的初始化代码中,我设置了一个 var self = this。我收到 'self.set is not a function' 错误。这是因为,查看调试器,当我声明 var self 时,this 指的是 'window'。我以前没见过这个。

谁能告诉我为什么 window 被选为 'this'

代码:

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

我想我已经解决了我的问题...语法。我是 Backbone 的新手,这是我为解决问题所做的更改。我愿意批评为什么这是正确的。

工作代码:

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

View 对象中没有 set 方法,也许您想要 setElement?

如果您碰巧发现 thiswindow 对象,很可能是因为您丢失了上下文。正如其他人指出的那样,self 变量分配没有理由。您可以使用 _.bind, _.bindAll 和其他方式来传递和设置上下文。

我试着清理你的例子,希望这对你有帮助:

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>