2015-07-11 76 views
1

我很難用我從API提取的集合初始化簡單視圖。當我嘗試從視圖中返回集合時,我嘗試的所有內容都返回一個空數組。視圖中的骨幹集合初始化

app.models.Employee = Backbone.Model.extend({ 

}); 

app.collections.Employees = Backbone.Collection.extend({ 

    Model: app.models.Employee, 
    url: "http://api.sample.com", 

    initialize: function(){ 
     this.fetch(); 
    }, 

    parse: function(response){ 
     console.log(response) 
    }, 

}); 

app.views.Container = Backbone.View.extend({ 
    el: $('.container'), 

    initialize: function(){ 
     this.collection = new app.collections.Employees(); 
     console.log(this.collection) 
     var that = this; 
     this.collection.fetch({ 
      success: function(){ 
       that.render(); 
      } 
     }); 
    }, 

    render: function(){ 
     console.log(this.collection) //returns no models 
    } 
}); 
+0

所以......它看起來像您可能通過將該console.log解析來阻止解析數據?嘗試刪除完全不必要的重寫解析方法? – billjamesdev

+1

而且你確實意識到你要調用兩次,對不對? – billjamesdev

回答

1

你必須正確地使用parse

parse: function(response) { 
    console.log(response); 
    return response; 
} //`,` - remove it at last item in object 
1

有3個問題,你的代碼

  • 您正在使用parse不正確。每

功能是通過原始響應對象,並應返回 陣列型號的規格屬性要添加到收藏

所以是的,如@謝爾蓋建議

parse: function(response) { 
    console.log(response); 
    return response; 
} 

或更好,只是刪除您的parse函數,不要覆蓋它。

  • 您正在呼叫您的fetch函數兩次。

在該行

this.collection = new app.collections.Employees(); 

最終調用這個函數

initialize: function(){ 
     this.fetch(); 
    }, 

第二次第一次是在查看您的初始化函數裏面。

3)你打破render

再次,同樣的事情,你parse。你應該

呈現從模型數據視圖模板,並更新 this.el新的HTML

像這樣的事情

render: function() { 
    this.$el.html(this.template(this.model.attributes)); 
    return this; 
    }