繁体   English   中英

骨干集合查看代码

[英]Backbone collection view code

我正在研究一个简单的.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)代码正常。

但是,如果我这样写是行不通的:

 //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:无法读取undefined的属性“ el”。

这是为什么 ?

您正在循环内使用return语句。 您只能返回一个结果。

render : function(){
  this.collection.each(function(tas){
    var t = new App.Views.Task({model : tas});
    this.$el.append(t.render().el);
  },this);

  return this;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM