Backbone'this'被设置为'window'

时间:2015-10-14 22:44:37

标签: javascript backbone.js underscore.js this

我正在尝试创建一个Backbone View对象。在我的初始化代码中,我设置了一个var self = this。我得到一个'self.set不是函数'错误。这是因为,看一下调试器,当我声明var self时,这指的是'window'。我以前没见过。

任何人都可以说明为什么选择“这个”窗口

代码:

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

2 个答案:

答案 0 :(得分:1)

set个对象中没有View方法,也许您想要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 });
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我想我已经找到了我的问题......语法。我是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);
}
});