2014-02-27 72 views
0

我正在研究一個簡單的主幹.js scipt。我有一個使用模型視圖形成的視圖集合。這裏是模型視圖:骨幹集合查看代碼

​​

現在的問題是,如果我寫這樣的集合視圖我的代碼工作:

//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)拋出遺漏的類型錯誤:無法讀取的未定義的屬性「厄爾尼諾」。

這是爲什麼?

+1

你爲什麼要在每個循環中返回這個? – Puigcerber

回答

0

您在循環中使用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; 
} 
+0

謝謝哈扎特。我太愚蠢了......顯而易見的是,回報正在制動循環。祝你今天愉快 ! –