【发布时间】:2014-02-27 10:04:36
【问题描述】:
我正在研究一个简单的主干.js scipt。我有一组使用模型视图形成的视图。这是模型视图:
//model view
App.Views.Task = Backbone.View.extend({
//receives model instance
tagName : 'li',
template : _.template($('#taskTemplate').html()),
render : function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
现在的问题是,如果我这样编写集合视图,我的代码就可以工作:
//collection view
App.Views.Tasks = Backbone.View.extend({
//receives collection instance
tagName : 'ul',
initialize : function(){ this.render() },
render : function(){
this.collection.each(function(tas){
var t = new App.Views.Task({model : tas});
this.$el.append(t.render().el);
}, this);
}
});
那么console.log(theview.el)代码就ok了。
但如果我这样写是行不通的:
//collection view
App.Views.Tasks = Backbone.View.extend({
//receives collection instance
tagName : 'ul',
render : function(){
this.collection.each(function(tas){
var t = new App.Views.Task({model : tas});
this.$el.append(t.render().el);
return this;
}, this);
}
});
对于此代码 console.log(theview.render().el) 抛出 Uncaught TypeError: Cannot read property 'el' of undefined 。
这是为什么呢?
【问题讨论】:
-
为什么要在每个循环中返回这个?