【问题标题】:Backbone collection view code主干集合视图代码
【发布时间】: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 。

这是为什么呢?

【问题讨论】:

  • 为什么要在每个循环中返回这个?

标签: javascript backbone.js


【解决方案1】:

您正在循环中使用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;
}

【讨论】:

  • 谢谢哈扎特。我太愚蠢了……显然返回正在制动循环。祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多